283.MoveZeroes

题目
283.MoveZeroes
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, nums should 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”移动到数组尾部,同时保持其余非零元素的相对位置不变。

例如,给定nums = [0, 1, 0, 3, 12],在调用你的函数之后,nums应该变为[1, 3, 12, 0, 0]。

备注:
你必须就地完成,不得复制该数组。
最小化总共的操作数。

(想看正解的跳过这段)这道题最初的想法是,先用循环将数组中为0的数的下标记录下来,然后在另一个循环中从被记录为0的地方开始,与下一个数依次两两交换,将第一个0移动到最后之后,再改动循环中数组的下标,改为第二个被记录为0的位置的下标。。。。。。。想象总是美好的,但是等写出来后暴露出一个很大的问题:随着一次次0被交换到最后,原先记录的数组中0的位置也随之改变,虽然每次只是前进一个位置,但是改完之后代码已经变得繁杂。
接下来换了种思路,只要保持相对位置不变就好了。当前的数字是0的话不做操作,非零的话将其与第一个零互换位置。
其核心在于这个第一个零的位置是如何变化的,即便一开始不是0也没关系,大不了让这个非零数和自己交换位置。
顺便贴上最优解的代码,思路和自解的差不多

package leetcode.array;

/**
 *      283.MoveZeroes
 *  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, nums should 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.
 *   @author 良
 */

//最优解
//class Solution {
//    public void moveZeroes(int[] nums) {
//        if(nums.length < 2) return;
//        int k = 0;
//        for(int i = 0; i < nums.length; i++) {
//            if(nums[i] != 0) {
//                nums[k++] = nums[i];
//            }
//        }
//        for(;k < nums.length; k++)
//            nums[k] = 0;


//        for (int i=0;i<nums.length;i++ )
//            System.out.print(nums[i]);
//    }
//}


//自解
class Solution {
    public void moveZeroes(int[] nums) {
        int j;
        for (int index = 0, current = 0; current < nums.length; current++) {
            if (nums[current] != 0){
                j=nums[index];
                nums[index]=nums[current];
                nums[current]=j;
                index++;
            }
        }
        for (int i=0;i<nums.length;i++ )
            System.out.print(nums[i]);
    }
}


public class MoveZeroes {
    public static void main(String[] args){
        Solution s=new Solution();
        int[] num={1,0,0,3,7,1,2,1,};
        s.moveZeroes(num);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值