LeetCode 移动零
https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/1/array/28/
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入:[0,1,0,3,12]
输出:[1,3,12,0,0]
说明:
- 必须在原数组上操作,不能拷贝额外的数组。
- 尽量减少操作次数。
此题有两个思路:
1. 采用类似于冒泡排序的思想,从后往前遍历,如果遇到0就把0和后面的数字交换位置,直到最后一个可用位置(需要记录)。时间复杂度是O(N^2),空间复杂度是O(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 index_range = range(len(nums)) 8 reverse_index_range = index_range[::-1] 9 available_location = len(nums) - 1 10 for i in reverse_index_range: 11 if nums[i] != 0: 12 continue 13 else: 14 j = i + 1 15 while True: 16 if j > available_location: 17 break 18 temp = nums[j-1] 19 nums[j-1] = nums[j] 20 nums[j] = temp 21 j = j + 1 22 available_location -= 1
2. 遍历第一次,将所有的非零值都移动到最前面,压缩的思想;遍历第二次,将前面压缩后的剩余空间都置0。时间复杂度是O(N),空间复杂度是O(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 available_location = 0 8 for i in range(len(nums)): 9 if nums[i] == 0: 10 continue 11 else: 12 nums[available_location] = nums[i] 13 available_location += 1 14 for i in range(available_location,len(nums)): 15 nums[i] = 0