[leetcode]283. Move Zeroes

这是leetcode第283题

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].

题目意思,就是把数组中的0都移动到数组的末尾,在保持其他元素相对顺序不变的情况下。

解题思路

2次遍历数组

第一次遍历,把不等于0的元素保存到另外一个数组中。
第二次遍历,先把已保存不等于0的元素依次赋值到nums,然后把nums剩下的元素空位都赋值0

public class Solution {
    public void moveZeroes(int[] nums) {
        ArrayList<Integer> nonZeroNumList = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nonZeroNumList.add(nums[i]);
            }
        }
        for (int i = 0; i < nonZeroNumList.size(); i++) {
            nums[i] = nonZeroNumList.get(i);
        }
        for (int i = nonZeroNumList.size(); i < nums.length; i++) {
            nums[i] = 0;
        }
    }
}

1次遍历数组

遍历过程有2个下标位偏移标记,分别是ij
i代表对于nums当前元素的偏移标记;
j代表遍历过程中,下一个不等于0的元素,应该存放在nums位置的偏移标记;

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

posted on 2016-05-18 23:31  wingyip  阅读(898)  评论(0编辑  收藏  举报

导航