[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实现

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

JavaScript实现

/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
   let cur = 0;
   for (let i = 0; i < nums.length; i++) {
   	if (nums[i] !== 0) {
   		nums[cur] = nums[i];
   		cur++;
   	}
   }
   while (cur < nums.length) {
   	nums[cur] = 0;
   	cur++;
   }
};

相关题目

283. Move Zeroes
2460. Apply Operations to an Array
posted @ 2019-10-23 02:22  CNoodle  阅读(137)  评论(0编辑  收藏  举报