4. Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 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)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

Code

/**
 * @author liyiheng
 */
public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        int count = (len1 + len2) / 2 + 1;

        int temp1 = 0, temp2 = 0;
        int index1 = 0, index2 = 0;

        for (int i = 0; i < count; i++) {
            temp1 = temp2;

            if (index1==len1){
                // use 2
                temp2 = nums2[index2];
                index2++;
            }else if (index2==len2){
                // use 1
                temp2 = nums1[index1];
                index1++;
            }else {
                // use the smaller one
                if (nums1[index1] < nums2[index2]) {
                    temp2 = nums1[index1];
                    index1++;
                } else {
                    temp2 = nums2[index2];
                    index2++;
                }
            }
        }
         if ((len1+len2)%2!=0){
            return temp2;
        }
      return   ((double) (temp1 + temp2))/2;
    }
}
發佈了21 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章