283. Move Zeroes

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.

将一个list本身按需求排序

solution

  • 准备用三种简单排序实现 题目要求除0外,保持原序列,没必要用平方复杂度
  1. 冒泡排序
class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        length = len(nums)
        for _ in range(length-1):
            flag = True
            for i in range(length-1):
                if nums[i] == 0:
                    flag = False
                    nums[i], nums[i+1] = nums[i+1], nums[i]
            length -= 1
            if flag:
                break

discuss

思路是记录排在最前面的0,当发现不为0的元素时,和最前面的0交换位置

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        last0 = 0
        for i in range(0,len(nums)):
            if (nums[i]!=0):
                nums[i],nums[last0] = nums[last0],nums[i]
                last0+=1

元素i遍历;nums[last0]当num[i]为0时不变,当nums[i]不为0时,交换元素,同时last0加1,指向0的最新位置

posted @ 2016-11-21 10:41  Salmd  阅读(108)  评论(0)    收藏  举报