Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ad390b3

Browse files
committed
第四题
1 parent 3e66d7f commit ad390b3

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

‎4.Median of Two Sorted Arrays.java

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*题目:
2+
There are two sorted arrays nums1 and nums2 of size m and n respectively.
3+
4+
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
5+
6+
Example 1:
7+
nums1 = [1, 3]
8+
nums2 = [2]
9+
10+
The median is 2.0
11+
Example 2:
12+
nums1 = [1, 2]
13+
nums2 = [3, 4]
14+
15+
The median is (2 + 3)/2 = 2.5
16+
17+
*/
18+
19+
/*解析:
20+
21+
要想找到中位数,就必须知道中位数的概念。从小到大排序的一列数,取其中的中间的数,如果长度是偶数的话取中间的两个数/2
22+
所以最重要,最核心的是:排序
23+
24+
如何将两个有序的数组,合并成一个有序的数组呢?
25+
算法:顺序扫描,每次将较小的元素放进结果数组中,和两个链表相加的题有些类似,可以复习一下之前的。这题不难。
26+
27+
复杂度:O(n)
28+
29+
*/
30+
31+
class Solution {
32+
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
33+
int[] result = new int[nums1.length+nums2.length];
34+
double median;
35+
//将数组1作为标准
36+
int i = 0;//数组1的临时变量
37+
int j = 0;//数组2的临时变量
38+
int count = 0;//结果数组的临时变量
39+
for( i = 0 ;i<nums1.length&&j<nums2.length;) {
40+
//将两者最小的数,放入目标数组
41+
if(nums1[i]>nums2[j]) {
42+
result[count++]=nums2[j++];
43+
}
44+
else{
45+
result[count++]=nums1[i++];
46+
}
47+
}
48+
//数组还有元素没有排好
49+
while(i<nums1.length){
50+
result[count++]=nums1[i++];
51+
}
52+
53+
while(j<nums2.length) {
54+
result[count++]=nums2[j++];
55+
}
56+
57+
//进行计算中位数
58+
if(result.length%2==0) {
59+
median=(result[result.length/2]+result[result.length/2-1])/2.0;
60+
61+
}
62+
else {
63+
median = result[result.length/2];
64+
}
65+
66+
return median;
67+
}
68+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /