【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));
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章