Python实现"移动零"的三种方法

给定数组nums,写一个函数将数组中所有零移动到数组尾,并且保持非零元素的相对位置不变

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

注意:

你必须在原数组上进行操作,不能拷贝额外的数组

最小化操作的次数

1:定义zeroP列表存放所有0元素的索引,访问数组时有规律的移动非零元素,并动态更新

def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        zeroPList = []    #存放所有0元素的下标
        for i, num in enumerate(nums):
            if num == 0 :
                zeroPList.append(i)
            elif len(zeroPList) != 0:
                index = zeroPList.pop(0)    #取出数组中最靠前的0元素下标
                nums[i], nums[index] = nums[index], nums[i]       #替换操作
                zeroPList.append(i)       #将更新后的0元素下标重新添加进数组中

2:先删除值为0的数,并累加0的个数j,最后在列表末尾添加j个0(参考他人代码)

def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        initLen = len(nums)
        i = 0    #累加计数
        j = 0    #0的个数
        while i + j < initLen:
            if nums[i] == 0:
                # del nums[i]
                nums[i:i+1] = []  #和被注释掉的语句效果一样
                j += 1
            else:
                i += 1
        nums += j*[0]

3:和第二种方法差不多,唯一的不同在于不用事先删除列表元素

def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        initLen = len(nums)
        i = 0    #累加计数
        j = 0    #不为0的个数
        while i < initLen:
            if nums[i] != 0:
                nums[j] =nums[i]
                j += 1
            i += 1
        nums[j:] = (len(nums)-j)*[0]

算法题来自:https://leetcode-cn.com/problems/move-zeroes/description/

你可能感兴趣的:(Algorithms)