283. Move Zeroes [LeetCode]

来源:互联网 发布:腾讯内部刷枪软件 编辑:程序博客网 时间:2024/06/02 03:22

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

题目意思很明确。从左到右遍历一个数组,每遇到一个0就把它移动到数组的最右端。且要求实现就地移动,尽量地少用操作步骤。

思路简析:观察发现,题目最终的结果数组里,非0元素序与原先数组中的非0元素序相同,其右边全是0。于是想到,可以设置一个指针下标从左到右遍历数组,另一个指针负责把遍历到的每一个非0元素记录到数组的最左侧。第一个指针遍历完成时,再将第二个指针右边的元素全部置0。因为在算法的实现过程中,第一个指针总是大于等于第二个指针的下标值,故不会影响到数组原先的数据。

具体实现的java代码如下:


0 0
原创粉丝点击