您的位置:首页 > 其它

移动零 Move Zeroes

2016-06-23 14:43 155 查看
https://leetcode.com/problems/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].

思路跟快排的第二种partition函数类似

class Solution {
public:
void moveZeroes(vector<int>& nums) {
int len = nums.size();
if (len <= 1){
return;
}
int i = -1;
for (int j = 0; j < len; j++){
if (nums[j] != 0){
swap(nums[++i], nums[j]);
}
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: