leetcode解题之移动零

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:

必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/move-zeroes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

开始时看题太快,理解错了,以为是要把0移动端末尾,其他元素升序排列,因为之前做过数组旋转,所以按照旋转的思路写了下面的代码:

class Solution {
    public void moveZeroes(int[] nums) {
       Arrays.sort(nums);
       for(int i=0;i<nums.length;i++){
           if(nums[i]!=0){
            for(int j=nums.length-1;j>0;j--)
                {
                    int tem = nums[j];
                    nums[j]=nums[j-1];
                    nums[j-1]=tem;
                 }
           }      
       }
    }
}

而题目中的意思是非零元素保持相对的位置,就是不改变排列的顺序,修改了多次,终于成功了,基本思路是遍历数组,遇到0则往后移动

class Solution {
    public void moveZeroes(int[] nums) {
        int end = nums.length;
        for(int i=0;i<end;){
            if(nums[i]==0&&i!=nums.length-1){
                 for(int j=i;j<nums.length-1;j++)
                {
                    int tem = nums[j+1];
                    nums[j+1]=nums[j];
                    nums[j]=tem;
                 } 
                 end--; 
            }else{
                i++;
            }
        }
    }
}

最后的版本,可以减少一部分移动

class Solution {
    public void moveZeroes(int[] nums) {
        int end = nums.length;
        for(int i=0;i<end;){
            if(nums[i]==0){
                 for(int j=i;j<end-1;j++)
                {
                    int tem = nums[j+1];
                    nums[j+1]=nums[j];
                    nums[j]=tem;
                 } 
                 end--; 
            }else{
                i++;
            }
        }
    }
}

评论里比较高效的写法

class Solution {
    public void moveZeroes(int[] nums) {
       //评论里通用的方法
       int index=0;
       for(int i=0;i<nums.length;i++){
           if(nums[i]!=0){//处理非0元素
               nums[index++]=nums[i];
           }
       }
        while(index<nums.length){//处理0
            nums[index++]=0;
        }

    }
}
发布了98 篇原创文章 · 获赞 0 · 访问量 3994

猜你喜欢

转载自blog.csdn.net/l888c/article/details/104562347