LeetCode: 283 Move Zeroes(easy)
Posted 玲珑子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode: 283 Move Zeroes(easy)相关的知识,希望对你有一定的参考价值。
题目:
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)的主要内容,如果未能解决你的问题,请参考以下文章