zoukankan      html  css  js  c++  java
  • 【LEETCODE】41、905. Sort Array By Parity

    package y2019.Algorithm.array;
    
    /**
     * @ProjectName: cutter-point
     * @Package: y2019.Algorithm.array
     * @ClassName: SortArrayByParity
     * @Author: xiaof
     * @Description: 905. Sort Array By Parity
     * Given an array A of non-negative integers, return an array consisting of all the even elements of A,
     * followed by all the odd elements of A.
     * You may return any answer array that satisfies this condition.
     *
     * Input: [3,1,2,4]
     * Output: [2,4,3,1]
     * The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
     *
     * @Date: 2019/7/3 8:48
     * @Version: 1.0
     */
    public class SortArrayByParity {
    
        public int[] solution(int[] A) {
            //先获取所有偶元素,然后获取所有奇元元素,还有一个方法就是交换前后位置
            //吧所有偶数放到前面,奇数放后面,类似快排
            int index1 = 0, index2 = A.length - 1;
            while(index1 < index2) {
                //遍历起始第一个不是偶数的位置
                while(index1 < A.length && (A[index1] & 1) == 0) {
                    index1++;
                }
                //后面往前,找到第一个不是奇数
                while(index2 > 0 && (A[index2] & 1) == 1) {
                    index2--;
                }
                //交换位置
                if(index1 < index2 && index1 < A.length && index2 > 0) {
                    //交换位置
                    int temp = A[index1];
                    A[index1] = A[index2];
                    A[index2] = temp;
                }
            }
    
            return A;
        }
    
        public static void main(String args[]) {
            int A[] = {3,1,2,4};
            SortArrayByParity fuc = new SortArrayByParity();
            System.out.println(fuc.solution(A));
        }
    }
  • 相关阅读:
    使用Speex中的AEC模块,提高声音质量(转)
    音频编解码speex库的使用方法
    VC 多线程编程(转)
    并口、串口、COM口区别
    用GDB调试程序
    [转]PCM文件格式
    PreTranslateMessage作用和使用方法
    音频编解码标准
    VS2010 运行速度加快方法(转)
    ON_COMMAND ON_MESSAGE ON_NOTIFY区别与联系
  • 原文地址:https://www.cnblogs.com/cutter-point/p/11128151.html
Copyright © 2011-2022 走看看