跳至主要內容

283. 移动零


283. 移动零open in new window

🟢   🔖  数组 双指针  🔗 力扣open in new window LeetCodeopen in new window

题目

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 <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1

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

题目大意

题目要求不能采用额外的辅助空间,将数组中 0 元素都移动到数组的末尾,并且维持所有非 0 元素的相对位置。

解题思路

这一题可以只扫描数组一遍,不断的用 i,j 标记 0 和非 0 的元素,然后相互交换,最终到达题目的目的。与这一题相近的题目有 第 26 题第 27 题第 80 题

代码

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

相关题目

题号标题题解标签难度
27移除元素open in new window[✓]数组 双指针
2460对数组执行操作open in new window数组 双指针 模拟