美文网首页
双指针 Leetcode 283 移动0

双指针 Leetcode 283 移动0

作者: 禾木清清 | 来源:发表于2019-07-17 18:47 被阅读0次

题目

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:

必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/move-zeroes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路1

每次找到0,放到最后面。
但是这种方法效率太低。

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        if not nums:
            return False
        
        i = 0
        length = len(nums)
        while i < length:
            if nums[i] == 0:
                nums[i:] = nums[i+1:] + [0] 
                length -= 1
            else:
                i += 1
                
        return nums
                

解题思路2

使用快慢指针,这种思路就是找到后面的非0依次保存到前面:

  • 快指针用来找后面的非0数字

  • 慢指针用来保存非0数字

  • 1.快指针找到后面的第一个非0数字,慢指针在第一个0;

    1. 如果fast != slow (相等的时候可能出现在开始都是非0数字),那么我们就交换两个数字。递增slow
  • 3.递增fast

代码

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        if not nums:
            return False
        
        fast = slow = 0
        
        while fast < len(nums):
            if nums[fast] != 0:
                if fast != slow:
                    nums[slow] = nums[fast]
                    nums[fast] = 0
                slow += 1
            fast += 1
                

相关文章

网友评论

      本文标题:双指针 Leetcode 283 移动0

      本文链接:https://www.haomeiwen.com/subject/asmclctx.html