• 【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));
        }
    
    }
  • 相关阅读:
    this指向问题
    原生js实现的金山打字小游戏(实例代码详解)
    js实现点赞效果
    .net core部署到linux可能碰到的问题
    Linux curl命令详解 Web程序
    用十年来学编程
    JAVA的字符串拼接与性能
    PHP学习的技巧和学习的要素总结
    php实现验证邮箱格式的代码实例
    PHP页面中文乱码处理办法
  • 原文地址:https://www.cnblogs.com/cutter-point/p/11128155.html
Copyright © 2020-2023  润新知