283. Move Zeroes(C++)
283. Move Zeroes
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]
.
题目大意:
给一个数组,将值为0的元素放置到最后,其他元素相对位置不变。
解题方法:
排序题,修改插入排序的判断条件就可以了
注意事项:
C++代码:
1 class Solution { 2 public: 3 void moveZeroes(vector<int>& nums) //仿插入排序 4 { 5 int j,tmp; 6 for(int p=1;p<nums.size();p++) 7 { 8 tmp=nums[p]; 9 for(j=p;j>0&&tmp!=0&&nums[j-1]==0;j--) 10 { 11 swap(nums[j],nums[j-1]); 12 } 13 nums[j]=tmp; 14 } 15 } 16 };
-------------------------------------------------------------------转账请注明出处。
--------------------------------------------------------------------如有好的建议或错误,请指出。