LeetCode905. 按奇偶校验排序数组

版权声明: https://blog.csdn.net/weixin_40550726/article/details/82817148

给定一个非负整数数组 A,返回一个由 A 的所有偶数元素组成的数组,后面跟 A 的所有奇数元素。

你可以返回满足此条件的任何数组作为答案。

示例:

输入:[3,1,2,4]
输出:[2,4,3,1]
输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。

提示:

  1. 1 <= A.length <= 5000
  2. 0 <= A[i] <= 5000

思路:双指针。

class Solution {
    public int[] sortArrayByParity(int[] A) {
         int startIndex=0;
        int endIndex=A.length-1;
        while(startIndex<endIndex){
            while(A[startIndex]%2==0){
                startIndex++;
                if(startIndex>=endIndex){
                    break;
                }
            }
            while(A[endIndex]%2!=0){
                endIndex--;
                if(startIndex>=endIndex){
                    break;
                }
            }
            if(startIndex>=endIndex){
                break;
            }
            int tmp=A[endIndex];
            A[endIndex]=A[startIndex];
            A[startIndex]=tmp;
        }
        return A;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40550726/article/details/82817148