LEETCODE42922. Sort Array By Parity II

Posted cutter-point

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LEETCODE42922. 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));
    

 

以上是关于LEETCODE42922. Sort Array By Parity II的主要内容,如果未能解决你的问题,请参考以下文章

LEETCODE41905. Sort Array By Parity

LeetCode --- 1122. Relative Sort Array 解题报告

LeetCode 905. Sort Array By Parity

leetcode360 - Sort Transformed Array - medium

[LeetCode&Python] Problem 905: Sort Array By Parity

LeetCode-912.Sort an Array