Leetcode 283. Move Zeroes
2016-01-28 12:50
429 查看
Given an array
to the end of it while maintaining the relative order of the non-zero elements.
For example, given
be
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
这道题要注意,是in place,
之后又想了一种方法。
与27. Remove Element 类似 https://leetcode.com/problems/remove-element/。 差别是把数组最后的元素置为0。
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.
这道题要注意,是in place,
public class Solution { public void moveZeroes(int[] nums) { if(nums.length<=1) return; int first = 0; int sec = 0; while(sec<nums.length) { //find first zero element while(first<nums.length && nums[first] !=0) { first++; } if(first == nums.length) return; sec = first+1; //find following first non-zero element while(sec<nums.length && nums[sec] == 0){ sec++; } if(sec == nums.length) return; swap(nums, first, sec); } } public void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
之后又想了一种方法。
与27. Remove Element 类似 https://leetcode.com/problems/remove-element/。 差别是把数组最后的元素置为0。
public class Solution { public void moveZeroes(int[] nums) { if(nums ==null|| nums.length == 0) return; int len = 0; for(int i =0; i < nums.length; i++){ if(nums[i] != 0){ if(nums[len]!=nums[i]) nums[len]=nums[i]; len++; } } // return len; for(int i = len; i < nums.length; i++){ nums[i] = 0; } } }
相关文章推荐
- 去年A轮融资的846家创业公司,现在快倒闭完了
- 知道可以做什么样的人,是成长的基础。
- js 导出excle之终极攻略(兼容各大浏览器),纯JS实现
- JFinal Model手动注册到TableMapping中的代码生成器
- android-IPC进程间通信
- 读书笔记 JavaScript 高级程序设计(第三版)-- 第2章
- 【Web前端】:JavaScript常用代码积累
- 使用ceph-deploy进行ceph安装
- ElasticSearch 2 (2) - Setup
- 机房收费系统合作版(三):利用备忘录模式实现取消修改基本数据
- SDK Hello world
- Excel破解密码代码
- android基础夯实2
- 性能测试项
- ceph分布式存储搭建经历
- NYOJ 476 谁是英雄 (唯一分解素数求因子个数)
- LRU Cache -- LeetCode
- C# 16进制与字符串、字节数组之间的转换
- 陌陌凭什么排中国iOS收入榜社交第一?无需惊奇
- Spring 源码分析(一) —— 迈向Spring之路