Skip to content

Commit c8a4f34

Browse files
committed
提交315 计算右侧小于当前元素的个数
1 parent 886ab7b commit c8a4f34

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<title>Document</title>
7+
</head>
8+
<body>
9+
<script>
10+
// Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/
11+
// Author : 悬笔e绝
12+
// Date : 2020-03-29
13+
14+
/**
15+
* @param {number[]} nums
16+
* @return {number[]}
17+
*/
18+
var countSmaller = function(nums) {
19+
// binary search
20+
function bSearch(target, a) {
21+
var start = 0
22+
, end = a.length - 1;
23+
while(start <= end) {
24+
var mid = ~~((start + end) >> 1);
25+
if (a[mid] >= target)
26+
end = mid - 1;
27+
else if (a[mid] < target)
28+
start = mid + 1;
29+
}
30+
return start;
31+
}
32+
33+
var tmp = [] // store
34+
, ans = [];
35+
for (var i = nums.length; i--; ) {
36+
var item = nums[i];
37+
38+
var index = bSearch(item, tmp);
39+
40+
ans.unshift(index);
41+
tmp.splice(index, 0, item);
42+
}
43+
return ans;
44+
};
45+
</script>
46+
</body>
47+
</html>

0 commit comments

Comments
 (0)