当前位置:网站首页>Leetcode question 283 Move zero

Leetcode question 283 Move zero

2022-07-06 20:14:00 Invite the wind to intoxicate the moon

subject

Given an array nums, Write a function that will 0 Move to end of array , While maintaining the relative order of non-zero elements .

Please note that , You must operate on the array in place without copying it .

Example 1:

Input : nums = [0,1,0,3,12]
Output : [1,3,12,0,0]
Example 2:

Input : nums = [0]
Output : [0]

Tips :

1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1

Advanced : Can you minimize the number of operations completed ?

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/move-zeroes
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Answer key : Double pointer ( Moving mode )

We define two pointers i,j, All traverse from the beginning ,i Go back first , When subscript is i The value of is not 0 when , Move the value to j Position of subscript , after j+1.j Recorded non 0 Number . Then subscript from j It has been assigned as 0

 Insert picture description here

class Solution {
    
    public void moveZeroes(int[] nums) {
    
        if(nums==null){
    
            return ;
        }
        
        // The first time you traverse ,j Pointer record non 0 The number of , As long as the time is not 0 All of are given to nums[j]
        int j=0;
        for(int i=0;i<nums.length;i++){
    
            if(nums[i]!=0){
    
                nums[j++]=nums[i];
            }
        }

        // Not 0 Element statistics are finished , Next, put j And the array after it is assigned 0 that will do 
        for(int i=j;i<nums.length;i++){
    
            nums[i]=0;
        }
    }
}

The time complexity is O(2n), That is to say O(n)

Answer key : Double pointer ( In exchange for )

It's also a double pointer i,j, Point back from the beginning , But when you encounter non 0 Elements , We'll exchange

class Solution {
    
    public void moveZeroes(int[] nums) {
    
        int j=0;
        for(int i=0;i<nums.length;i++){
    
            if(nums[i]!=0){
    
                swap(nums,i,j);
                j++;
            }
        }
        
    }
    public void swap(int [] nums,int i,int j ){
    
        int temp=nums[j];
        nums[j]=nums[i];
        nums[i]=temp;
    }    

}
原网站

版权声明
本文为[Invite the wind to intoxicate the moon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131228213567.html