Leetcode 283 Move zeros

来源:互联网 发布:linux 重启后挂载失败 编辑:程序博客网 时间:2024/04/26 07:35

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 的数字 

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

0 0
原创粉丝点击