[LeetCode] 283. Move Zeroes

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.

Example 1:

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

Example 2:

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

Constraints:

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

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

移动零。

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

题意很直观,将数组中所有 0 移动到数组的末端。要求不能使用额外空间。

思路是给一个 cur 指针和一个 i 指针,用 i 去遍历数组。当数组遇到非 0 的数字的时候,就放到 cur 的位置,cur++。如果扫描完整个数组 cur 的位置没有到达数组末尾,后面的位置用 0 补齐。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public void moveZeroes(int[] nums) {
 3         int cur = 0;
 4         for (int i = 0; i < nums.length; i++) {
 5             if (nums[i] != 0) {
 6                 nums[cur] = nums[i];
 7                 cur++;
 8             }
 9         }
10         while (cur < nums.length) {
11             nums[cur] = 0;
12             cur++;
13         }
14     }
15 }

JavaScript实现

 1 /**
 2  * @param {number[]} nums
 3  * @return {void} Do not return anything, modify nums in-place instead.
 4  */
 5 var moveZeroes = function(nums) {
 6     let cur = 0;
 7     for (let i = 0; i < nums.length; i++) {
 8         if (nums[i] !== 0) {
 9             nums[cur] = nums[i];
10             cur++;
11         }
12     }
13     while (cur < nums.length) {
14         nums[cur] = 0;
15         cur++;
16     }
17 };

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/11723729.html