logseq_notes/pages/OJ notes/pages/Leetcode Move-Zeroes.md
2023-06-14 14:27:22 +08:00

1.5 KiB

Leetcode Move-Zeroes

2022-07-11 09:55

Algorithms:

#algorithm #two_pointers #array_in_place_operation

Data structures:

#DS #array

Difficulty:

#coding_problems #difficulty_easy

Additional tags:

#leetcode

Revisions:

N/A

Problem

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Follow up: Could you minimize the total number of operations done?

Examples

Example 1:

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

Example 2:

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

Constraints

Constraints:

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

Thoughts

[!summary] This is a #array_in_place_operation problem.

Because the data can be overwritten, and zeros can be predicted in the result array, I use in-place array operations.

Solution

class Solution {
public:
void moveZeroes(vector<int> &nums) {
  // Tow pointers, since data can be overwritten and one pointer is faster
  // than another.
  int num = 0;

  for (int i = 0; i < nums.size(); i++) {
    if (nums[i] != 0) {
      nums[num++] = nums[i];
    }
  }

  for (int j = num; j < nums.size(); j++) {
    nums[j] = 0;
  }
}
};