Leetcode283. Move Zeroes

Leetcode283. Move Zeroes

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:

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

两种in-place算法

设定一个临时变量 k = 0,遍历数组 nums ,将非零元素移动到 nums[k] 位置,同时 k++,而后将[k,….nums.size()]中的元素置零。

public void moveZeroes(vector<int>& nums) {
     
    int k = 0; // nums中, [0...k)的元素均为非0元素
    // 遍历到第i个元素后,保证[0...i]中所有非0元素
    // 都按照顺序排列在[0...k)中
    for(int i = 0 ; i < nums.size() ; i ++)
        if(nums[i])
            nums[k++] = nums[i];
    // 将nums剩余的位置放置为0
    for(int i = k ; i < nums.size() ; i ++)
        nums[i] = 0;
}

Leetcode283. Move Zeroes_第1张图片

设定一个临时变量 k = 0,遍历数组 nums,将非零元素与之前的零元素进行交换,维护变量k的值。

public void moveZeroes(vector<int>& nums) {
     
    int k = 0; // nums中, [0...k)的元素均为非0元素

    // 遍历到第i个元素后,保证[0...i]中所有非0元素
    // 都按照顺序排列在[0...k)中
    // 同时, [k...i] 为 0
    for(int i = 0 ; i < nums.size() ; i ++){
     
        if(nums[i]){
     
            if(k != i){
     
                swap(nums[k++] , nums[i]);
            }else{
     
                k ++;
            }
        }
	}
}

Leetcode283. Move Zeroes_第2张图片

图片来源:五分钟学算法

你可能感兴趣的:(leetcode)