Skip to content

Commit c418fa8

Browse files
committed
Sliding Window Median
1 parent 6f17940 commit c418fa8

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Source : https://leetcode.com/problems/sliding-window-median/
2+
// Author : Han Zichi
3+
// Date : 2017-01-22
4+
5+
/**
6+
* @param {number[]} nums
7+
* @param {number} k
8+
* @return {number[]}
9+
*/
10+
var medianSlidingWindow = function(nums, k) {
11+
let ans = []
12+
, res = nums.slice(0, k);
13+
14+
let findMedian = () => {
15+
if (k & 1)
16+
return res[k >> 1];
17+
else {
18+
let a = (k >> 1) - 1
19+
, b = k >> 1;
20+
return (res[a] + res[b]) / 2;
21+
}
22+
};
23+
24+
res.sort((a, b) => a - b);
25+
26+
ans.push(findMedian());
27+
28+
for (let i = k, len = nums.length; i < len; i++) {
29+
let insertPos = binarySearch2(res, nums[i]);
30+
res.splice(insertPos, 0, nums[i]);
31+
32+
let delPos = binarySearch(res, nums[i - k]);
33+
res.splice(delPos, 1);
34+
35+
ans.push(findMedian());
36+
}
37+
38+
return ans;
39+
};
40+
41+
/**
42+
* 查找有序数组中第一次出现某数的位置,如果没找到,返回 -1
43+
* @param {number[]} a 从小到大排列的有序数组
44+
* @param {number} target 需要查找的元素值
45+
* @return {number} 数组下标,如果没找到,该值为 -1
46+
*/
47+
function binarySearch(a, target) {
48+
var start = 0
49+
, end = a.length - 1;
50+
51+
while (start <= end) {
52+
var mid = (start + end) >> 1;
53+
if (a[mid] >= target)
54+
end = mid - 1;
55+
else
56+
start = mid + 1;
57+
}
58+
59+
return a[start] === target ? start : -1;
60+
}
61+
62+
/**
63+
* 查找有序数组中刚好比某数大的元素位置,如果所有数都比该数小,则返回 a.length
64+
* @param {number[]} a 从小到大排列的有序数组
65+
* @param {number} target 需要查找的元素值
66+
* @return {number} 数组下标
67+
*/
68+
function binarySearch2(a, target) {
69+
target += 1;
70+
var start = 0
71+
, end = a.length - 1;
72+
73+
while (start <= end) {
74+
var mid = (start + end) >> 1;
75+
if (a[mid] >= target)
76+
end = mid - 1;
77+
else
78+
start = mid + 1;
79+
}
80+
81+
return start;
82+
}

0 commit comments

Comments
 (0)