Move Zeros

来源:互联网 发布:中国名门望族排名,知乎 编辑:程序博客网 时间:2024/04/27 13:35

问题描述:

把数组的非0元素往前移动,0元素往后移动。要求do this in-place without making a copy of the array


解决:

因为空间复杂度的要求,不能创建一个数组来保存原数组中的非0元素。可以使用双指针来解决,与前面大部分的题类似做法。


/* * 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:You must do this in-place without making a copy of the array.Minimize the total number of operations. */public class MoveZeros {    public void moveZeroes(int[] nums) {        if(nums == null || nums.length == 0)         return;        int index = 0;        for(int i=0; i<nums.length; i++) {        if(nums[i]!=0) {        nums[index++] = nums[i];        }        }        for(int i=index; i<nums.length; i++) {        nums[i] = 0;        }    }}
一次遍历结束之后,做了把所有非0元素前移的工作。此外我们还需要把数组剩余的元素修改为0。


原创粉丝点击