2

LeetCode-283-移动零

 2 years ago
source link: https://segmentfault.com/a/1190000040685785
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LeetCode-283-移动零

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

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:数组遍历

首先,声明一个变量theLastNotZeroPos用来记录最后一个非0的位置,然后从后往前遍历数组nums,如果数组的元素等于0,则需要进行如下处理:

  • 如果当前位置等于theLastNotZeroPos,则将theLastNotZeroPos减一,继续遍历下一个元素;
  • 如果当前位置不等于theLastNotZeroPos,则将当前位置的后一位到theLastNotZeroPos的所有元素全部前移一位,然后想theLastNotZeroPos位置的元素改为0,并且将theLastNotZeroPos减一,然后处理下一个元素。

遍历完成后,即为移动后的结果。

public class LeetCode_283 {
    public static void moveZeroes(int[] nums) {
        // 最后一个非0的位置
        int theLastNotZeroPos = nums.length - 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (nums[i] == 0) {
                if (i != theLastNotZeroPos) {
                    for (int j = i; j < theLastNotZeroPos; j++) {
                        nums[j] = nums[j + 1];
                    }
                    nums[theLastNotZeroPos] = 0;
                }
                theLastNotZeroPos--;
            }
        }
    }

    public static void main(String[] args) {
        int[] nums = new int[]{0, 1, 0, 3, 12};
        System.out.println("-----移动前-----");
        for (int num : nums) {
            System.out.print(num + " ");
        }
        System.out.println();
        moveZeroes(nums);
        System.out.println("-----移动后-----");
        for (int num : nums) {
            System.out.print(num + " ");
        }
    }
}

【每日寄语】 生活的不确定性,正是我们希望的来源。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK