python--leetcode 283. Move Zeroes
来源:互联网 发布:php中不等于符号 编辑:程序博客网 时间:2024/06/06 13:26
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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
这一题就是给你一个list,里面都是数字,让你在不新开list的情况下,把0全部移到最后,并最小化操作次数。
O(n)复杂度内能解决,遍历一遍list就行,无非是list的操作。
代码:
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ i,count=0,0 while(i<len(nums)): if(nums[i]==0): del nums[i] nums.append(0) i=i-1 i=i+1 count=count+1 if(count==len(nums)):breaks=Solution()a=[0,2,0,1,0]print(s.moveZeroes(a))print(a)或者直接互换位置,用zero记录零的位置:
def moveZeroes(self, nums): zero = 0 # records the position of "0" for i in xrange(len(nums)): if nums[i] != 0: nums[i], nums[zero] = nums[zero], nums[i] zero += 1
阅读全文
1 0
- leetcode 283. Move Zeroes python
- [leetcode: Python]283. Move Zeroes
- python--leetcode 283. Move Zeroes
- 【LeetCode】283. Move Zeroes
- Leetcode 283. Move Zeroes
- LeetCode #283. Move Zeroes
- 283. Move Zeroes LeetCode
- LeetCode 283. Move Zeroes
- LeetCode 283. Move Zeroes
- LeetCode 283. Move Zeroes
- 【LeetCode】283. Move Zeroes
- leetcode 283. Move Zeroes
- leetcode 283. Move Zeroes
- LeetCode 283. Move Zeroes
- leetcode 283. Move Zeroes
- #leetcode#283. Move Zeroes
- LeetCode *** 283. Move Zeroes
- LeetCode 283. Move Zeroes
- C++中继承的总结
- Android开发—智能家居系列-----智能家居原理
- 面向连接的运输:TCP
- 姿态识别
- linux下的emacs修改配置
- python--leetcode 283. Move Zeroes
- Kibana
- dubbo -6监控中心的介绍与简易版的安装
- TCP 3次握手的通俗理解
- 单点登录之CAS原理和实现
- 【WEB】说说JSONP
- java线程间通信——等待唤醒机制
- FFmpeg 视音频同步
- 11-14