- 283 移动零 ---- 双指针
- 来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number - 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
- 换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != i 且 nums[j] < nums[i] 。
- 示例 2:
输入:nums = [6,5,4,8]
输出:[2,1,0,3]
解题思路:双指针:left指针本身指向0,其左侧是已经处理完的数组,全部是非0,right是未处理数组的开始,指向非0的数,其左侧到left指针处均为0。遍历整个数组,right不断向右移,当遇到非0时,则交换left和right内容,left向右移,right至数组末尾结束。(在遇到第一个0之前,left和right一直指向同一个,遇到第一个0,left指向它,而right会跳到下一个非0数时才交换两者位置,left+1,这样将非0数换到之前left的位置,left向右移始终指向第一个0.)
// c++
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int left =0, right =0;
while(right<nums.size()){
if(nums[right]!=0){
swap(nums[left],nums[right]);
++left;
}
++right;
}
}
};
# python 3
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
left, right = 0,0
while right< len(nums):
if nums[right] != 0:
nums[left], nums[right] = nums[right], nums[left]
left +=1
right +=1