-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy path1608-special-array-with-x-elements-greater-than-or-equal-x.js
76 lines (69 loc) · 1.47 KB
/
1608-special-array-with-x-elements-greater-than-or-equal-x.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* @param {number[]} nums
* @return {number}
*/
const specialArray = function(nums) {
let l = -1, r = 1001
while(l <= r) {
const mid = r - Math.floor((r - l) / 2)
const tmp = valid(mid)
if(tmp === mid) return mid
else if(tmp > mid) l = mid + 1
else r = mid - 1
}
return -1
function valid(mid) {
let res = 0
for(let e of nums) {
if(e >= mid) res++
}
return res
}
};
// another
/**
* @param {number[]} nums
* @return {number}
*/
const specialArray = function (nums) {
nums.sort((a, b) => b - a)
let i = 0
while(i < nums.length && nums[i] >= i) {
i++
}
if(nums[i - 1] < i) return -1
return i
};
// another
/**
* @param {number[]} nums
* @return {number}
*/
const specialArray = function(nums) {
nums.sort((a, b) => b - a)
let left = 0, right = nums.length
while(left <= right) {
const mid = left + ((right - left) >> 1)
if(mid < nums[mid]) left = mid + 1
else right = mid - 1
}
// if we found i == nums[i], there will be i + 1 items
// larger or equal to i, which makes array not special.
return left < nums.length && left === nums[left] ? -1 : left
};
// another
/**
* @param {number[]} nums
* @return {number}
*/
const specialArray = function(nums) {
const n = nums.length
nums.sort((a, b) => b - a)
let l = 0, r = n
while(l < r) {
const mid = l + ((r - l) >> 1)
if(nums[mid] > mid) l = mid + 1
else r = mid
}
return l < n && l === nums[l] ? -1 : l
}