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

题目描述:将数组到零移到最后,并保持不为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++;
            }
        }        
        
    }
}

猜你喜欢

转载自www.cnblogs.com/smallone/p/12122706.html