标签:
一、前言
题是上周五做的,开始思路有点问题,考虑不全,导致submit了3次才AC。
二、题283 Move Zeroes
Given an array
nums
, write a function to move all0
‘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:
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.
看到题目第一反应就是把非0项取出放入另一个list,再补全0,但是题目明确说了 without making a copy of the array,于是作罢。
三、解题思路
取出0项对应list中的位置,从后往前删除0项,删一项补一项(补0),这样对应关系才不变。
代码如下,runtime:88ms。
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ count=0 tags=[] for num in nums: count+=1 if num == 0: if str(count-1) not in tags: tags.append(count-1) for tag in tags[::-1]: del nums[tag] nums.append(0)
觉得这样不简洁,又看了下discuss里的优秀解法,也记录一下。
把非0项从前往后放,在list后补0。runtime:80ms。
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ k=0 #step1:move all none zero numbers to the front for num in nums: if num!=0: nums[k]=num k+=1 nums[k:]=[0]*(len(nums)-k) #step2: set the rest of the list to be zero
Leetcode刷题记录[python]——283 Move Zeroes
标签:
原文地址:http://www.cnblogs.com/Myoungs/p/5520397.html