zoukankan      html  css  js  c++  java
  • Lintcode: Merge Sorted Array II

    Merge two given sorted integer array A and B into a new sorted integer array.
    
    Example
    A=[1,2,3,4]
    
    B=[2,4,5,6]
    
    return [1,2,2,3,4,4,5,6]
    
    Challenge
    How can you optimize your algorithm if one array is very large and the other is very small?

    没什么好说的,Arraylist来做merge, 建一个新ArrayList

     1 class Solution {
     2     /**
     3      * @param A and B: sorted integer array A and B.
     4      * @return: A new sorted integer array
     5      */
     6     public ArrayList<Integer> mergeSortedArray(ArrayList<Integer> A, ArrayList<Integer> B) {
     7         // write your code here
     8         if (A==null || A.size()==0) return B;
     9         if (B==null || B.size()==0) return A;
    10         ArrayList<Integer> res = new ArrayList<Integer>();
    11         int i=0, j=0;
    12         for (int k=0; k<A.size()+B.size(); k++) {
    13             if (i<A.size() && j<B.size() && A.get(i) < B.get(j)) {
    14                 res.add(A.get(i));
    15                 i++;
    16             }
    17             else if (i<A.size() && j<B.size() && A.get(i) >= B.get(j)){
    18                 res.add(B.get(j));
    19                 j++;
    20             }
    21             else if (i<A.size()) {
    22                 res.add(A.get(i));
    23                 i++;
    24             }
    25             else {
    26                 res.add(B.get(j));
    27                 j++;
    28             }
    29         }
    30         return res;
    31     }
    32 }
  • 相关阅读:
    将maven项目托管到github
    HDOJ_1215_七夕节
    HDOJ_1108_最小公倍数
    HDOJ_1061_Rightmost Digit
    HDON_1021_Fibonacci Again
    HDOJ_1008_Elevator
    HDOJ_1235_统计同成绩学生人数
    HDOJ_2006_求奇数的乘积
    HDOJ_1201_18岁生日
    HDOJ_1019_大二写_Least Common Multiple
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4340934.html
Copyright © 2011-2022 走看看