My answer:
class Solution { public void moveZeroes(int[] nums) { if (nums == null || nums.length < 1) { return; } int count = 0; for (int i = 0; i < nums.length; i ++) { if (nums[i] == 0) { count ++; continue; } nums[i - count] = nums[i]; } // clear the last number of #{count} elements to 0 for (int i = nums.length - 1; i > nums.length - 1 - count; i --) { nums[i] = 0; } } }
Better answer: this method actually is using variable "left" to keep 0s position, and "right" to keep non-0 position. "right" is always increasing, while "left" doesn't change if 0 is encountered.
class Solution { public: void moveZeroes(vector<int>& nums) { int left = 0, right = 0; while (right < nums.size()) { if (nums[right]) { swap(nums[left++], nums[right]); } ++right; } } };
No comments:
Post a Comment