zoukankan      html  css  js  c++  java
  • LeetCode Median of Two Sorted Arrays

    There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

     1 public class Solution {
     2     public double findMedianSortedArrays(int A[], int B[]) {
     3         int la=A.length;
     4         int lb=B.length;
     5         int l=la+lb;
     6         int ia=0,ib=0;
     7         ArrayList<Integer> list = new ArrayList<Integer>();
     8         for (int i = 0; i < l; i++) {
     9             if (ia < la && ib < lb) {
    10                 if (A[ia] < B[ib]) {
    11                     list.add(A[ia]);
    12                     ++ia;
    13                 } else {
    14                     list.add(B[ib]);
    15                     ++ib;
    16                 }
    17             }else if (ia >= la && ib < lb) {
    18                 list.add(B[ib]);
    19                 ++ib;
    20             }else if (ia < la && ib >= lb) {
    21                 list.add(A[ia]);
    22                 ++ia;
    23             }
    24 
    25             if (list.size() == l / 2 + 1) {
    26                 if (l % 2 == 1) {
    27                     return list.get(list.size() - 1);
    28                 } else {
    29                     double last1 = list.get(list.size() - 1);
    30                     double last2 = list.get(list.size() - 2);
    31                     return (last1 + last2) / 2;
    32                 }
    33             }
    34             
    35             
    36         } 
    37 
    38         return 0;
    39 
    40     }
    41 }
  • 相关阅读:
    ZOJ2913Bus Pass(BFS+set)
    HDU1242 Rescue(BFS+优先队列)
    转(havel 算法)
    ZOJ3761(并查集+树的遍历)
    ZOJ3578(Matrix)
    HDU1505
    ZOJ3574(归并排序求逆数对)
    VUE-脚手架搭建
    VUE脚手架搭建
    VUE-node.js
  • 原文地址:https://www.cnblogs.com/birdhack/p/4181358.html
Copyright © 2011-2022 走看看