【LEETCODE】42、922. Sort Array By Parity II

package y2019.Algorithm.array;

/**
 * @ProjectName: cutter-point
 * @Package: y2019.Algorithm.array
 * @ClassName: SortArrayByParityII
 * @Author: xiaof
 * @Description: 922. Sort Array By Parity II
 * Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.
 * Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.
 * You may return any answer array that satisfies this condition.
 *
 * Input: [4,2,5,7]
 * Output: [4,5,2,7]
 * Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
 *
 * 有一个数组A,其中奇元素和偶元素的数量相等。请把A排序,使得奇元素位于奇数位置,偶元素位于偶数位置。任何满足上述条件的排序都是合法的。
 *
 * @Date: 2019/7/3 17:54
 * @Version: 1.0
 */
public class SortArrayByParityII {


    public int[] solution(int[] A) {
        //定义2个索引,第一指向奇数索引,第二个偶数索引
        int oddIndex = 1;
        int evenIndex = 0;
        while(oddIndex < A.length && evenIndex < A.length) {
            while(oddIndex < A.length && (A[oddIndex] & 1) == 1) {
                oddIndex += 2;
            }

            while (evenIndex < A.length && (A[evenIndex] & 1) == 0) {
                evenIndex += 2;
            }

            //交换位置
            if(oddIndex < A.length && evenIndex < A.length) {
                int temp = A[oddIndex];
                A[oddIndex] = A[evenIndex];
                A[evenIndex] = temp;
                oddIndex += 2;
                evenIndex += 2;
            }
        }

        return A;
    }

    public static void main(String args[]) {
        int A1[] = {2,3};
        SortArrayByParityII fuc = new SortArrayByParityII();
        System.out.println(fuc.solution(A1));
    }

}
原文地址:https://www.cnblogs.com/cutter-point/p/11128155.html