LeetCode 905. Sort Array By Parity

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

Return any array that satisfies this condition.

Example 1:

Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Example 2:

Input: nums = [0]
Output: [0]

Constraints:

  • 1 <= nums.length <= 5000
  • 0 <= nums[i] <= 5000

把一个数组里偶数放在前面,奇数放在后面。

自己的想法就是用two pointers分别指向前后,前面的如果遇到奇数就记下来,后面的如果遇到偶数就记下来,前后都有了以后就互相交换就完事了。于是就写了如下的代码,debug了巨久,各种corner case……感觉非常不优雅。

class Solution {
    public int[] sortArrayByParity(int[] nums) {
        int start = 0;
        int end = nums.length - 1;
        while (start < end) {
            while (start < nums.length && nums[start] % 2 == 0) {
                start++;
            }
            // now nums[start] is odd
            while (end >= 0 && nums[end] % 2 != 0) {
                end--;
            }
            // now nums[end] is even
            // swap nums[start] and nums[end]
            if (start < end) {
                int temp = nums[start];
                nums[start] = nums[end];
                nums[end] = temp;
                start++;
                end--;
            }
        }
        return nums;
    }
}

于是去solutions溜达了一圈,大家的想法都大差不差,但是很明显大家都不像我这么贪心,在while里还加while来想一次找到需要交换的start和end,而可以一步步来,这样会更清晰,也不用这么多corner case的条件。

class Solution {
    public int[] sortArrayByParity(int[] nums) {
        int start = 0;
        int end = nums.length - 1;
        while (start < end) {
            if (nums[start] % 2 == 0) {
                start++;
            } else {
                if (nums[end] % 2 == 0) {
                    int temp = nums[start];
                    nums[start] = nums[end];
                    nums[end] = temp;
                    start++;
                } 
                end--;
            }
        }
        return nums;
    }
}

后面又写到一道题的时候看了下也有人用我最开始写的while的方法,于是refine了一下,让它变得更优雅了,那我更喜欢这种做法了:

class Solution {
    public int[] sortArrayByParity(int[] nums) {
        int start = 0;
        int end = nums.length - 1;
        while (start < end) {
            while (start < end && nums[start] % 2 == 0) {
                start++;
            }
            while (start < end && nums[end] % 2 != 0) {
                end--;
            }
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
        }
        return nums;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值