问题描述:
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入:[0,1,0,3,12]
输出:[1,3,12,0,0]
说明:
- 必须在原数组上操作,不能拷贝额外的数组。
- 尽量减少操作次数。
方法1:检测到为0纪录0的个数,不为0时进行赋值运算nums[i - k] = nums[i]
最后将检测到的0补到nums的最后
1 class Solution(object): 2 def moveZeroes(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: void Do not return anything, modify nums in-place instead. 6 """ 7 if len(nums) == 2: 8 if nums[0] == 0: 9 nums[0],nums[1] = nums[1],nums[0] 10 return 11 else: 12 return 13 k = 0 14 for i in range(len(nums)): 15 if nums[i] == 0: 16 k += 1 17 elif nums[i] != 0 : 18 nums[i - k] = nums[i] 19 for j in range(len(nums) - k,len(nums)): 20 nums[j] = 0
方法2:每次将元素等于0的位置变成[]。
1 class Solution(object): 2 def moveZeroes(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: void Do not return anything, modify nums in-place instead. 6 """ 7 i = 0 8 length = len(nums) 9 while i < len(nums): 10 while nums != [] and nums[i] == 0: 11 nums[i:i+1] = [] 12 if i == len(nums): 13 break 14 i += 1 15 nums += (length - len(nums))*[0]
将方法1改进:
1 class Solution(object): 2 def moveZeroes(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: void Do not return anything, modify nums in-place instead. 6 """ 7 length = len(nums) 8 i = 0 9 n = 0 10 while i + n < length: 11 if nums[i] == 0: 12 n += 1 13 del nums[i] 14 else: 15 i += 1 16 nums += [0]*n
2018-09-23 09:07:49