LeetCode第283题

LeetCode第283题:移动零

题目详述

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序

解法一

双指针联动跑,j指向零元素,i指向非零元素,交换num[i]和nums[j]的值,保证非零元素相对顺序。

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

解法二

解法一的plus版,增加判断,减少了交换次数

public void moveZeroes(int[] nums){
    int j = 0; 
    for (int i = 0; i < nums.length; i++ ) {
        if(nums[i] != 0) {
            nums[j] = nums[i];
            if(i != j) nums[i] = 0;
            j++;
        }
    }
}
发布了40 篇原创文章 · 获赞 0 · 访问量 662

猜你喜欢

转载自blog.csdn.net/weixin_42610002/article/details/104065569
今日推荐