LeetCode-OJ
2015-09-23 13:35
267 查看
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.
思路:用两个指针,从头开始,向后
public static void moveZeroes(int[] nums) {
int first=0;
int second=0;
while(second<nums.length) {
if(nums[second]!=0) {
if(second != first) {
nums[first++] = nums[second];
nums[second] = 0;
}
else{
first++;
}
}
second++;
}
}
static void printarray(int []array){
for(int i = 0;i<array.length;i++){
System.out.println(array[i]);
}
}
public static void main(String[] args){
int []nums = new int[]{0, 1, 0, 3, 12};
moveZeroes(nums);
printarray(nums);
}
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 static void moveZeroes(int[] nums) {
int first=0;
int second=0;
while(second<nums.length) {
if(nums[second]!=0) {
if(second != first) {
nums[first++] = nums[second];
nums[second] = 0;
}
else{
first++;
}
}
second++;
}
}
static void printarray(int []array){
for(int i = 0;i<array.length;i++){
System.out.println(array[i]);
}
}
public static void main(String[] args){
int []nums = new int[]{0, 1, 0, 3, 12};
moveZeroes(nums);
printarray(nums);
}
相关文章推荐
- spring中常被忽视的注解 @Primary
- Codeforces Round #320 (Div. 2)
- matlab矩阵函数操作
- 新浪云Git代码仓库使用入门
- 将 Sublime 3 打造成 Python/Django IDE开发利器
- cf 580 c(邻接表+dfs)
- apache-archiva-2.2.0 密码过期问题的解决
- 修改时区(RHEL6.5)
- YII2中Codeception的安装
- ksh 运算符
- cf 580B
- Git的使用和相关配置
- 数据入库总结
- leetcode - Missing Ranges
- 著名的英文搜索引擎
- 程序员迷茫的感情生活
- 登录时旋转等待效果
- 重载和多态之间的关系?!(C++初学者)
- MySQL DBA 面试全揭秘
- python3 入门 (二) 列表的使用