[LeetCode] 905. Sort Array By Parity

题目描述

Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.

Example 1:

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

具体解法 

 最简单的就是建立两个指针,左指针从左到右找奇数,右指针从右到左找偶数,然后进行交换,这里要注意不要越界

class Solution {
    public int[] sortArrayByParity(int[] A) {

        if(A == null || A.length == 0){

            return A;
        }

        // 让左边是偶数,右边是奇数
        int left = 0;
        int right = A.length - 1;

        while(left <= right){

            // 在左边找到第一个奇数
            while(left <= right && A[left] % 2 == 0){

                left++;
            }

            // 在右边找到第一个偶数
            while(left <= right && A[right] % 2 != 0){

                right--;
            }

            if(left > right){

                break;
            }

            swap(A, left, right);
        }

        return A;
    }

    private void swap(int[] a, int left, int right) {

        int temp = a[left];
        a[left] = a[right];
        a[right] = temp;

    }
}

猜你喜欢

转载自blog.csdn.net/zhttly/article/details/83281300
今日推荐