class Solution { public: void moveZeroes(vector<int>& nums) { for(int i = 0, j = 0; i < nums.size(); i++) { if(nums[i]) { swap(nums[i],nums[j++]); } } } }; //2nd approach class Solution { public: void moveZeroes(vector<int>& nums) { int zero = 0, one = 0, n = nums.size()-1; while(zero < n && one < n) { while(zero < n && nums[zero] != 0) { zero++; } one = zero; while(one < n && nums[one] == 0) { one++; } swap(nums[zero],nums[one]); zero++; } } };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter