首页 > 编程语言 > 详细

leetcode.293 将数组中到零移到最后

时间:2019-12-31 09:45:19      阅读:73      评论:0      收藏:0      [点我收藏+]

题目描述:将数组到零移到最后,并保持不为0到数相对位置不变

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.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

思路:

1. 设立变量 count 记录当前遍历过到0到数量, index记录连续的0的第一个0的索引值,tmp临时记录当前遍历到的不为0的那个数

2. 遍历数组

   index初始值为-1

 若当前遍历的值nums[i] == 0 那么就让count++

   否则 让tmp=nums[i] ,然后判断index是否为负数,是的话就让index=0,然后将当前nums[i] =0,再让nums[index]=tmp, index++

遍历完成就实现了将零放到最后

代码实现:

class Solution {
    public void moveZeroes(int[] nums) {
        // 思路
        // 1.设置变量 count 记录当前零数量 
        // tmp记录当前遍历到到值, 
        // index 记录当前已放在前面到不为0到最后一个元素到索引
        // 2.遍历数组,发现当前值为0 count++ 
        //   若当前值不为0 那么就将tmp=当前值,并从index 开始往后移动一位,最后将 nums[index+1]=tmp
        int count = 0;
        int tmp;
        int index=-1;
        for(int i =0; i< nums.length;i++){
            if(nums[i]==0){
                count++;
            }else{
                tmp = nums[i];
                if(index<0){
                    index =0;
                }
                nums[i]=0;
                nums[index]=tmp;
                index++;
            }
        }        
        
    }
}

 

leetcode.293 将数组中到零移到最后

原文:https://www.cnblogs.com/smallone/p/12122706.html

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