zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    pytest_04
    pytest_03
    pytest_02
    CF 1416C XOR Trie
    CF 1413D
    ZOJ 3725 概率dp
    ZOJ 3726
    位运算
    CF1439C 线段树
    unordered_set
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/12440742.html
Copyright © 2011-2022 走看看