Java [Leetcode 283]Move Zeroes
2015-12-22 09:45
543 查看
题目描述:
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.
解题思路:
将数组中的非零数字往前压缩,剩余的位置补零。
代码如下:
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 void moveZeroes(int[] nums) { int pos = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] != 0){ nums[pos++] = nums[i]; } } for(; pos < nums.length; pos++) nums[pos] = 0; } }
相关文章推荐
- Java工程师成神之路~
- [springframework] - Spring MVC Implements RESTful
- 使用eclipse和maven生成java web程序war包
- Dubbo与Zookeeper、SpringMVC整合和使用(负载均衡、容错)
- 解决java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver问题
- java jdk1.7常量池移到哪去了?
- Caused by: java.lang.UnsatisfiedLinkError: Couldn't load zbar: findLibrary returned null
- Java 理论与实践: 正确使用 Volatile 变量
- spring xml namespace
- jdk1.7
- Ibator插件安装、配置及使用说明
- spring mvc default-servlet mvc:resources mvc:default-servlet-handler区别
- spring mvc default-servlet mvc:resources mvc:default-servlet-handler区别
- Java C# MD5 加密串一致性
- Java 实现当当网泄露数据快速检索
- 四道Java基础题 你能对几道?
- 使用Java开发多线程端口扫描工具 推荐
- java模拟浏览器下载图片
- java实现ftp上传下载(jdk1.7以上)
- Java 8 时间日期库的20个使用示例