数组-leetcode 283. Move Zeroes

来源:互联网 发布:sql查询分析器在破解 编辑:程序博客网 时间:2024/06/08 18:40

原题链接:Move Zeros


思路分析:将元素0移动到数组末端并保持非0元素相对顺序不变,而且要in-place。

使用双指针,一个指针遍历,另一个指针始终保持指向数组前段非0元素的最后一个

遍历指针遍历完,将指向指针之后的元素都置0即可;


题解:

public class Solution {    public void moveZeroes(int[] nums) {        /*            Time Complexity:O(N)            Space Complexity:O(1)        */        int i=-1;        for(int j=0;j<nums.length;j++){            if(nums[j]!=0){                i++;                nums[i]=nums[j];            }        }        i++;        while(i<nums.length){            nums[i]=0;            i++;        }    }}



原创粉丝点击