移动零 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函数类似
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]); } } } };