Given an array
nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
For example, given
nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [1, 3, 12, 0, 0]
.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
Solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
void moveZeroes(vector<int>& nums) { | |
vector<int> zerosCount(nums.size(), 0); | |
int c=0; | |
for(int i=0; i<nums.size(); i++){ | |
if(nums[i]==0){ | |
c++; continue; | |
}else{ | |
zerosCount[i]=c; | |
} | |
} | |
for(int i=0; i<nums.size(); i++){ | |
if(zerosCount[i]==0) | |
continue; | |
nums[i-zerosCount[i]]=nums[i]; | |
nums[i]=0; | |
} | |
} | |
}; |
Round 2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
void moveZeroes(vector<int>& nums) { | |
int zeros=0; | |
for(int i=0; i<nums.size(); i++){ | |
if(nums[i]==0){ | |
zeros++; | |
}else{ | |
nums[i-zeros]=nums[i]; | |
nums[i]=zeros>0? 0:nums[i]; | |
} | |
} | |
} | |
}; |
No comments:
Post a Comment