LeetCode 922. Sort Array By Parity II (按奇偶排序数组 II)

题目标签:Sort

  利用两个指针,在偶数位置上找到第一个奇数;在奇数位置上找到第一个偶数,然后互相转换数字。

  具体看code。

 

Java Solution: 

Runtime:  2ms, faster than 99.61% 

Memory Usage: 42.9MB, less than 29.63%

完成日期:03/06/2020

关键点:two pointers

class Solution {
    public int[] sortArrayByParityII(int[] A) {
        int i = 0, j = 1, len = A.length;
        
        while(i < len && j < len) {
            // i starts from index 0, stops if found a odd
            while(i < len && A[i] % 2 == 0) {
                i += 2;
            }
            
            // j starts from index 1, stops if found a even
            while(j < len && A[j] % 2 == 1) {
                j += 2;
            }
            
            if(i < len && j < len) {
                swap(A, i, j);
            }    
        }
        return A;
    }
    
    private void swap(int[] A, int i, int j) {
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
    }
}

参考资料:LeetCode Discuss

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2020-03-08 05:44  Jimmy_Cheng  阅读(217)  评论(0编辑  收藏  举报