-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path283.MoveZeroes.cpp
More file actions
55 lines (50 loc) · 1.24 KB
/
Copy path283.MoveZeroes.cpp
File metadata and controls
55 lines (50 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
public:
/*
------ this fails few cases. check the mistake ------
vector<int> leftshift(vector<int> &nums,int i, int n){
while(i<n-1){
nums[i]=nums[i+1];
i++;
}
nums[n-1]=0;
return nums;
}
void moveZeroes(vector<int>& nums) {
//check if nums[i] is zero then left shift by one place
int n = nums.size();
for(int i=0;i<n;i++){
if(nums[i]!=0){
i++;
}else{
nums = leftshift(nums,i,n);
}
}
*/
void moveZeroes(vector<int>& nums) {
int n = nums.size();
int j = 0;
for(int i = 0; i < n; i++){
if(nums[i] != 0){
swap(nums[i], nums[j++]);
}
}
/*
using extra space ---------------------
vector<int>temp;
int count = 0;
for(int i=0; i<nums.size();i++){
if(nums[i] != 0){
temp.push_back(nums[i]);
}else{
count++;
}
}
while(count){
temp.push_back(0);
count--;
}
nums = temp;
*/
}
};