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

Posted 几米空间

tags:

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

以上是关于LeetCode 922. Sort Array By Parity II (按奇偶排序数组 II)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 922 Sort Array By Parity II 解题报告

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

Leetcode 922. Sort Array By Parity II

922. Sort Array By Parity II

LEETCODE42922. Sort Array By Parity II

922. Sort Array By Parity II