leetcode Median of Two Sorted Arrays
来源:互联网 发布:淘宝评价不支持传图 编辑:程序博客网 时间:2024/06/04 01:24
leetcode 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
思路
这道题目其实比我们想象中的要简单一点,因为当我们看到两个有序数组的时候,自然而然就会往二分搜索或者归并排序上去思考。这到题目的想法就是利用归并排序找到第k个小的数,这个k能根据我们数组的长度算出其中位数。
public double find(int []nums1,int nums2[],int mid) { int i,j,k; int []temp = new int[nums1.length + nums2.length]; for (i = 0,j = 0,k = 0;k <= mid;) { if (i >= nums1.length) { temp[k++] = nums2[j++]; } else if (j >= nums2.length) { temp[k++] = nums1[i++]; } else if (nums1[i] < nums2[j]) { temp[k++] = nums1[i++]; } else { temp[k++] = nums2[j++]; } } return temp[mid]; } public double findMedianSortedArrays(int[] nums1, int[] nums2) { int m = nums1.length; int n = nums2.length; if (((m + n) & 1) == 1) {//如果其是奇数 return find(nums1, nums2, (m + n) >> 1); } else { return (find(nums1,nums2,(m + n ) >> 1) + find(nums1, nums2, (m + n - 1) >> 1)) / 2; } } public void test1() { int []nums1 = {1,3}; int []nums2 = {2}; System.out.println("test1的结果:"+findMedianSortedArrays(nums1, nums2)); } public void test2() { int []nums1 = {1,2}; int []nums2 = {3,4}; double value = findMedianSortedArrays(nums1, nums2); System.out.println("test2:"+value); } public void test3() { int []nums1 = {}; int []nums2 = {1}; System.out.println("test3:"+findMedianSortedArrays(nums1, nums2)); }
0 0
- LeetCode: Median of Two Sorted Arrays
- LeetCode Median of Two Sorted Arrays
- leetcode 26: Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- [Leetcode] Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- leetcode Median of Two Sorted Arrays
- LeetCode-Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays
- [leetcode] Median of Two Sorted Arrays
- leetcode-004:Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- leetcode之 median of two sorted arrays
- 【转载】【leetcode】Median of Two Sorted Arrays
- LeetCode - Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- RabbitMQ原理简单介绍
- ZZULI 1922: A
- HIHO #1181 : 欧拉路·二(fleury算法输出欧拉路径)
- 双系统的小旅行
- 协方差矩阵
- leetcode Median of Two Sorted Arrays
- leetcode 349. Intersection of Two Arrays, 350. Intersection of Two Arrays II
- 城市列表索引
- POJ3069 Saruman's Army
- poj 1019 Number Sequence(打表+二分)
- Struts2 入门示例
- Pro Android学习笔记(一四四):触摸屏(3):多点触摸
- UVA 11427 Expect the Expected
- 学习笔记3——32位和64位Linux操作系统的区别及系统识别方法