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/

  • 相关阅读:
    29-赫夫曼树
    28-线索化二叉树
    27-顺序存储二叉树
    26-二叉树的遍历查找和删除
    25-二叉树的概念
    24-逻辑结构分析
    23-哈希表
    22-查找算法
    21-堆排序
    Mui-列表/table-view
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/12440742.html
Copyright © 2011-2022 走看看