283. Move Zeroes
2016-05-04 15:18
211 查看
题目:
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.
题意:将给定数组中的0元素后移到数组末尾,并保持数组中非0元素的顺序;
解题思路:顺序比较,将非零元素前移,结束之后补零。
代码:
C++版:
java版:
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.
题意:将给定数组中的0元素后移到数组末尾,并保持数组中非0元素的顺序;
解题思路:顺序比较,将非零元素前移,结束之后补零。
代码:
C++版:
class Solution{ public: void moveZeroes(vector<int>& nums){ int index = 0; for(int i=0; i<nums.size(); i++){ if(nums[i]!=0) nums[index++] = nums[i]; } for(; index<nums.size(); index++){ nums[index] = 0; } } };
java版:
public class Solution{ public void moveZeroes(int[] nums){ if(nums==null || nums.length==0) return; int index = 0; for(int num : nums){ if(num!=0) nums[index++] = num; } while(index<nums.length){ nums[index++] = 0; } } }
相关文章推荐
- mongodb 3.0以上需要的jar包
- 畅想音乐播放器第二版
- YII 学习之修改默认控制器
- 第六课等于之对象相加——C#计算器编程教学
- javaweb学习总结(十九)——JSP标签
- iOS 多线程--NSThread
- red5源码分析---3
- C#学习:委托摘录 《自学系列》
- Xcode插件失效问题解决办法
- String转换成json格式(一):net.sf.json.JSONObject
- 淘宝存储系统tair的安装
- Activity与service间的Messenger通信方式
- python 查找文件夹下面的所有文件,读取文件
- javascript开发中如何使用face++,得到人脸数据(如何简单获取图片url,如何获取完整的人脸信息)
- hadoop jar
- 【华为OJ】【009-提取不重复的整数】
- 夜想——来到烟大的前因
- HDU 1874 畅通工程续
- 第三届山东ACM Pick apples
- React-Native设置入口组件的问题,新手需注意