leetcode笔记--Move Zeroes
来源:互联网 发布:windows xp字体大小 编辑:程序博客网 时间:2024/06/01 10:45
Move Zeroes
题目:难度(Easy)
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.
Tags:Array,Two Pointers
分析:要求:就地更改数组,并且使得所有的操作最小
法1:就统计非0数的个数,缺点:可能遍历2遍数组,时间复杂度O(n)
代码实现:
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ n = len(nums) countOfNoZero = 0 for i in range(n): if nums[i]: nums[countOfNoZero] = nums[i] countOfNoZero += 1 for i in range(countOfNoZero, n): nums[i] = 0
法2:双指针,时间复杂度O(n)
代码实现:
class Solution(object): #双指针 def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ n = len(nums) i, j = 0, 0#i指向第一个0,j指向第一个非0 while j < n and i<n: while j<n and nums[j]==0: j += 1 while i<n and nums[i]!=0: i += 1 if j == n or i == n: break if j>i:#只有出现在第一个0的后面的非0数才需要移动,并占据第一个0 的位置 nums[i] = nums[j] nums[j] = 0 else:#第一个非0数在第一个0的前面,不需要移动,则需要寻找下一个可能需要移动的非0数 j += 1
0 0
- leetcode笔记:Move Zeroes
- leetcode笔记--Move Zeroes
- LeetCode笔记:283. Move Zeroes
- leetcode 283: Move Zeroes
- leetcode - Move Zeroes
- Leetcode: Move Zeroes
- LeetCode - Move Zeroes
- LeetCode-Move Zeroes
- [LeetCode]Move Zeroes
- leetcode-283-Move Zeroes
- [leetcode 283]Move Zeroes
- LeetCode---Move Zeroes
- LeetCode 283----Move Zeroes
- LeetCode Move Zeroes
- LeetCode Move Zeroes
- Leetcode #283 Move Zeroes
- leetcode: (283) Move Zeroes
- [LeetCode 283] Move Zeroes
- 在 Linux 下你所不知道的 df 命令的那些功能
- LabVIEW 中使用dll
- JDK安装与环境变量配置
- linux驱动程序中的异步编程
- how websites tracking u
- leetcode笔记--Move Zeroes
- node安装相关
- emacs + vim = spacemacs 安装
- 顺序表的简单实现
- OpenStack Mitaka 中Ceph支持Discard
- 前端案例--纯css3实现怪异选项卡
- browser user agent
- AngularJS学习相关
- MySQL 视图技术