首页 > 其他 > 详细

LeetCode 283: Move Zeroes

时间:2020-05-15 22:36:00      阅读:35      评论:0      收藏:0      [点我收藏+]

LeetCode 283: Move Zeroes

题意描述

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

注:(1)不能复制数组

(2)尽可能少的移动数组元素

解题思路

一、思路一

  1. 遍历数组,使用一个临时变量记录第一个0的位置J
  2. 如果J后面的元素非0则进行交换,更新J的索引
  3. 如果J后面的元素为0,则继续向后遍历,直到遇到非0的元素,与J交换位置,更新J的索引,J指向第二个0
  4. 遍历数组结束,J指向最后一个0,并且前面的0已经移动到最后一个0后面
    public void moveZeroes(int[] nums) {
            int j = 0;
            for(int i=0;i<nums.length;i++){
                if(nums[i] != 0){	
                    int temp = nums[j];
                    nums[j] = nums[i];
                    nums[i] = temp;
                    j++;
                }
            }
        }

二、思路二

  1. 遍历数组,使用count记录遍历过程中0的个数
  2. 如果nums【i】不为0,则向前移动count位
  3. 将数组后count位置0
    public void moveZeroes(int[] nums) {
            int count = 0;
            int len = nums.length;
            for(int i=0;i<len;i++){
                if(nums[i] == 0) count ++;
                if(nums[i] != 0) nums[i-count] = nums[i];
            }
            for(int i=0;i<count;i++){
                nums[len-count+i] = 0;
            }
        }

LeetCode 283: Move Zeroes

原文:https://www.cnblogs.com/le-le/p/12897561.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!