leetcode 283:Move Zeroes
2015-09-20 18:36
190 查看
题目:
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.
思路:
算法时间复杂度 最坏为n2,感觉可以为n,类似于快排(二次的时候,考虑优化)代码:
public class Solution { public void moveZeroes(int[] nums) { int flag =0, count = 0; for(int i=0; i<nums.length-1; i++) { if(nums[i] == 0) { for(int j=i+1; j<nums.length; j++) { flag = 0; if(nums[j] != 0) { nums[i] = nums[j]; nums[j] = 0; flag = 1; count ++; break; } } } if(flag ==0 && count>0) break; } } }
相关文章推荐
- Nginx Location配置总结
- 顺序表的基本操作(创建,遍历,查找,删除,归并)
- java连接sql server 2008和连接sql server 2008(完整版)
- SQL Server
- xmpp协议学习笔记
- 我对GIT的理解
- 【codevs1049】
- mkyaffs2image编译
- 华为机试题2
- Keepalive实现Mysql主主复制,高可用群集
- HD 5455 FangFang
- C++ 数组
- 【codevs】2918
- yaffs2文件镜像制作工具yaffs2image
- 软工实践练习——使用git进行代码管理心得
- 数据库语句总结(2)
- BA--暖通系统常见设计细节要点
- mysql授权
- Java学习手手记-一元二次函数解法
- 二维数组取值