您的位置:首页 > 其它

leetcode第4题——***Median of Two Sorted Arrays

2015-12-29 09:52 525 查看

题目

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)).

思路

要求出两个有序数组(长度分别为m和n)的中位数,并且要求时间复杂度为O(log (m+n))。可以利用归并排序的思想,将两个数组归并排序为一个有序数组,然后取中位数即可。但这样做出来的时间复杂度好像是O(m+n),不知为什么仍然通过了= =,就先把代码贴出来吧,以后想到更符合的算法再改进。

代码

Python

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        nums = []
        i,j = 0,0
        for k in range(len(nums1) + len(nums2)):
            if (i < len(nums1)) & (j < len(nums2)):
                if nums1[i] < nums2[j]:
                    nums.append(nums1[i])
                    i += 1
                else:
                    nums.append(nums2[j])
                    j += 1
            elif i < len(nums1):
                nums.append(nums1[i])
                i += 1
            elif j < len(nums2):
                nums.append(nums2[j])
                j += 1
        if(len(nums)%2):
            return float(nums[len(nums)/2])
        else:
            return (nums[len(nums)/2 - 1] + nums[len(nums)/2])/float(2)


Java

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] nums = new int[nums1.length + nums2.length];
        int i = 0;
        int j = 0;
        for(int k = 0;k < nums1.length + nums2.length;++k)
        {
            if(i < nums1.length && j < nums2.length)
            {
                if(nums1[i] < nums2[j])
                {
                    nums[k] = nums1[i];
                    ++i;
                }
                else
                {
                    nums[k] = nums2[j];
                    ++j;
                }
            }
            else if(j < nums2.length)
            {
                nums[k] = nums2[j];
                ++j;
            }
            else if(i < nums1.length)
            {
                nums[k] = nums1[i];
                ++i;
            }
        }
        
        if(nums.length%2 == 1)
            return (double)nums[(nums.length-1)/2];
        else
            return (nums[nums.length/2-1] + nums[nums.length/2])/((double)2);
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: