Move Zeroes

来源:互联网 发布:投诉数据分析ppt 编辑:程序博客网 时间:2024/06/05 16:07

题目地址:https://leetcode.com/problems/move-zeroes/

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.

这个题目有点意思,就是把0都放在后面,把非零的数字放在前面。

要是不保证非零元素的顺序,那就容易多了,直接交换即可,但是人家题目要求保持原序。

另外如果按照顺序表去处理(其实也就是顺序表),每移除一个0,后面的元素就往迁移,那这个移动次数无疑也很多,所以得想办法尽量少做移动的操作。

我们可以这么做:

找两根指针p和q,p指向每次迭代的第一个0的位置,q指向每次迭代的第一个非0的位置。每次就交换这两个位置的元素就可以了,准确滴说不算交换,还是移动。

代码实现如下:

public class MoveZeroes {    public void moveZeroes(int[] nums) {        if (nums.length < 2)            return;        int p = 0;        int q = 0;        while (p < nums.length && nums[p] != 0) p++;        q = p;        while (q < nums.length && nums[q] == 0) q++;        while (q < nums.length) {            nums[p] = nums[q];            nums[q] = 0;            while (p < nums.length && nums[p] != 0) p++;            while (q < nums.length && nums[q] == 0) q++;        }    }    public static void main(String[] args) {        MoveZeroes zeroes = new MoveZeroes();        int[] nums = {0,0};        zeroes.moveZeroes(nums);        for (int i = 0; i < nums.length; i++)            System.out.println(nums[i]);    }}

这个代码的时间复杂度是:O(n)

0 0
原创粉丝点击