adding iterator exercise
This commit is contained in:
@@ -162,4 +162,4 @@ also defined.
|
||||
## 9.9 Leetcode Exercises
|
||||
|
||||
- [Leetcode problem 27: Remove Element](https://leetcode.com/problems/remove-element/). Solution: [p27_removeelement.cpp](../../leetcode/p27_removeelement.cpp)
|
||||
- [Leetcode problem 263: Ugly Number](https://leetcode.com/problems/ugly-number/). Solution: [p263_uglynumber.cpp](../../leetcode/p263_uglynumber.cpp)
|
||||
- [Leetcode problem 283: Remove Zeroes](https://leetcode.com/problems/move-zeroes/). Solution: [p283_movezeroes.cpp](../../leetcode/p283_movezeroes.cpp)
|
||||
|
||||
21
leetcode/p283_movezeroes.cpp
Normal file
21
leetcode/p283_movezeroes.cpp
Normal file
@@ -0,0 +1,21 @@
|
||||
class Solution {
|
||||
public:
|
||||
void moveZeroes(vector<int>& nums) {
|
||||
vector<int>::iterator itr = nums.begin();
|
||||
// use itr2 to represent the "new" vector
|
||||
vector<int>::iterator itr2 = nums.begin();
|
||||
while(itr != nums.end()){
|
||||
// traverse the vector and store all non-zero elements in the "new" vector.
|
||||
if(*itr != 0){
|
||||
*itr2 = *itr;
|
||||
itr2++;
|
||||
}
|
||||
itr++;
|
||||
}
|
||||
// as we skipped zeroes above, we now fill them in.
|
||||
while(itr2!=nums.end()){
|
||||
*itr2 = 0;
|
||||
itr2++;
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user