leetcode(283). Move Zeroes

来源:互联网 发布:nginx 伪静态配置 编辑:程序博客网 时间:2024/06/08 05:25

problem

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].

Note: You must do this in-place without making a copy of the array.
Minimize the total number of operations.

solution

当一开始p指向的不是零的时候逐渐增加直到遇到第一个零,之后p表示最前面的零的位置,并逐渐交换遍历到的非零的数。

class Solution(object):    def moveZeroes(self, nums):        """        :type nums: List[int]        :rtype: void Do not return anything, modify nums in-place instead.        """        p = 0        for i, num in enumerate(nums):            if num == 0:                continue            else:                nums[p], nums[i] = nums[i], nums[p]                p += 1
class Solution(object):    def moveZeroes(self, nums):        p = 0        for i, num in enumerate(nums):        # 这样修改后的if-else语句更加简洁            if num != 0:                nums[p], nums[i] = nums[i], nums[p]                p += 1
原创粉丝点击