LeetCode: 283 Move Zeroes(easy)
阿新 • • 發佈:2017-09-06
com opera tail edits stat cas end cal note
題目:
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:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
代碼:
不知道為什麽,在本地可以運行,提交上去顯示 Submission Result: Runtime Error ,感覺可能是越界?不知道。。調不出來了。。(把0和後面非0的交換)
1 class Solution { 2 public: 3 vector<int> moveZeroes(vector<int>& nums) { 4 for(auto zero = nums.begin(); zero < nums.end(); zero++){ 5 if ( *zero == 0 ){ 6 auto notzero = zero; 7 for(notzero; notzero < nums.end(); notzero++){ 8 if(*notzero != 0) 9 break; 10 }
11 if (zero != notzero) 12 iter_swap(zero, notzero); 13 } 14 } 15 return nums; 16 } 17 };
換個思路(把後面非0的元素和前面的0元素交換):
1 class Solution { 2 public: 3 void moveZeroes(vector<int>& nums) { 4 int last = 0, cur = 0; 5 while(cur < nums.size()) { 6 if(nums[cur] != 0) { 7 swap(nums[last], nums[cur]); 8 last++; 9 } 10 cur++; 11 } 12 } 13 };
別人的代碼:
1 class Solution { 2 public: 3 void moveZeroes(vector<int>& nums) { 4 int nonzero = 0; 5 for(int n:nums) { 6 if(n != 0) { 7 nums[nonzero++] = n; 8 } 9 } 10 for(;nonzero<nums.size(); nonzero++) { 11 nums[nonzero] = 0; 12 } 13 } 14 };
LeetCode: 283 Move Zeroes(easy)