Skip to content

Commit cd7005e

Browse files
committed
leetcode 4
1 parent 48199c5 commit cd7005e

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
- 92.Reverse Linked List II `medium` `linked list` [link](https://leetcode.com/problems/reverse-linked-list-ii/description/) [code](./leetcode/92.js)
2323
- 2.Add Two Numbers `medium` `linked list` [link](https://leetcode.com/problems/add-two-numbers/description/) [code](./leetcode/2.js)
2424
- 3.Longest Substring Without Repeating Characters `medium` `string` [link](https://leetcode.com/problems/longest-substring-without-repeating-characters/description/) [code](./leetcode/3.js)
25+
- 4.Median of Two Sorted Arrays `hard` `array` [link](https://leetcode.com/problems/median-of-two-sorted-arrays/description/) [code](./leetcode/4.js)
2526

2627
## lintcode
2728

leetcode/4.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
4. Median of Two Sorted Arrays
3+
4+
5+
There are two sorted arrays nums1 and nums2 of size m and n respectively.
6+
7+
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
8+
9+
You may assume nums1 and nums2 cannot be both empty.
10+
11+
Example 1:
12+
13+
nums1 = [1, 3]
14+
nums2 = [2]
15+
16+
The median is 2.0
17+
18+
19+
Example 2:
20+
21+
nums1 = [1, 2]
22+
nums2 = [3, 4]
23+
24+
The median is (2 + 3)/2 = 2.5
25+
*/
26+
27+
/**
28+
* @param {number[]} nums1
29+
* @param {number[]} nums2
30+
* @return {number}
31+
*/
32+
var findMedianSortedArrays = function (nums1, nums2) {
33+
const len = nums1.length + nums2.length;
34+
35+
let i = 0; j = 0;
36+
let current, last;
37+
38+
while (i + j <= len / 2) {
39+
last = current;
40+
41+
if (nums1[i] === undefined) {
42+
current = nums2[j++];
43+
continue;
44+
}
45+
46+
if (nums2[j] === undefined) {
47+
current = nums1[i++];
48+
continue;
49+
}
50+
51+
if (nums1[i] <= nums2[j]) {
52+
current = nums1[i++];
53+
} else {
54+
current = nums2[j++];
55+
}
56+
}
57+
58+
return len % 2 == 0 ? (last + current) / 2 : current;
59+
};
60+
61+
console.log(findMedianSortedArrays([1, 3], [2]));
62+
console.log(findMedianSortedArrays([1, 2], [3, 4]));

0 commit comments

Comments
 (0)