[LeetCode]: 283: Move Zeroes
2015-09-21 22:22
344 查看
题目:
Given an array
For example, given
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
分析:从后向前逐一查找即可
代码:
网上高手的思路:现将非0的数前移,再将余下的空位补0
代码:
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,
numsshould 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.
分析:从后向前逐一查找即可
代码:
public class Solution { public static void moveZeroes(int[] nums) { for(int i =nums.length-1; i >=0 ;i--){ if(nums[i] ==0){ int intTemp = 0; for(int j=i+1;j<nums.length;j++){ if(nums[j]!= 0){ nums[j-1] = nums[j]; nums[j] = 0; } } } } } }
网上高手的思路:现将非0的数前移,再将余下的空位补0
代码:
public class Solution { public static void moveZeroes(int[] nums) { int iCounter = 0; for(int i =0;i<nums.length;i++){ if(nums[i] ==0){ iCounter++; } else{ nums[i-iCounter] = nums[i]; } } for(int i = (nums.length-iCounter);i<nums.length;i++){ nums[i]=0; } } }
相关文章推荐
- windows下svn自动更新
- C# web 链接数据库问题二三(一)
- Codeforces #320 Div1 解题报告
- Hadoop 笔记之shuffle详解过程
- 数据库之创建表&向表中插入数据
- Create Command Line Tools
- "不忍直视"的ViewHolder模式
- jdbc至sql server的两种常见方法
- 遍历一个文件夹下的所有文件和子文件夹
- Django 通用视图
- Redis和Memcached的区别
- I Hate It
- featurelayer的方法
- CoreText<1>
- iOS在文件末尾写入内容
- UVA 156 Ananagrams
- Peeking Iterator
- NuGet的几个小技巧
- hdoj 5443 The Water Problem【线段树求区间最大值】
- android官方培训教程