Monday, April 25, 2016

LeetCode Q283: Move Zeros

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:
  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

Solution:

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:
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];
}
}
}
};
view raw gistfile1.txt hosted with ❤ by GitHub

No comments:

Post a Comment