283. Move Zeroes [Leetcode][C++]
Mayank Arora
Posted on December 24, 2021
All suggestions are welcome. Please upvote if you like it. Thank you.
Leetcode Problem Link: 283. Move Zeroes
Brute Force Solution:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
// Brute Force Solution Time O(N) & Auxiliary Space O(N)
vector<int> a;
int count=0;
for(int i=0;i<nums.size();i++){
if(nums[i]==0)
count++;
else
a.push_back(nums[i]);
}
while(count--)
a.push_back(0);
for(int i=0;i<nums.size();i++){
nums[i]=a[i];
}
}
};
Efficient Solution:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
// Efficient Solution Time O(N) & Auxiliary Space O(1)
int lt=0,rt=0,n=nums.size();
while(rt<n){
if(nums[rt]==0)
rt++;
else{
int temp=nums[lt];
nums[lt]=nums[rt];
nums[rt]=temp;
lt++;
rt++;
}
}
}
};
All suggestions are welcome. Please upvote if you like it. Thank you.
💖 💪 🙅 🚩
Mayank Arora
Posted on December 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.