LeetCode 283. Move Zeroes (移动零)

时间:2023-08-23 22:16:17

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.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

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

题目标签:Array, Two Pointers

  题目给了我们一个nums array, 让我们把所有的0 都移动到最后面,保留其他数字的排序。

  利用two pointers p1 和 p2, 基本思想是让p2停留在0的数字上,让p1找到不是0的数字,对换p1 p2的值。

  遍历nums array,当遇到0的话,p1++;当遇到不是0的数字,对换p1 和 p2的值,p1++ p2++。

Java Solution:

Runtime beats 74.14%

完成日期:04/27/2017

关键词:Array, Two Pointers

关键点:找到不是0的数字,与0置换

 public class Solution
{
public void moveZeroes(int[] nums)
{
int p1 = 0; // iterate each number
int p2 = 0; // stop at 0 while(p1 < nums.length)
{
if(nums[p1] != 0) // find the non-zero number
{
if(p1 != p2) // swap non-zero number with zero number
{ // if p1 = p2, no need to swap
int temp = nums[p1];
nums[p1] = nums[p2];
nums[p2] = temp;
} p2++;
} p1++;
} }
}

参考资料:N/A

LeetCode 算法题目列表 - LeetCode Algorithms Questions List