-
Notifications
You must be signed in to change notification settings - Fork 225
/
1060-missing-element-in-sorted-array.js
101 lines (86 loc) · 1.91 KB
/
1060-missing-element-in-sorted-array.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
Given a sorted array A of unique numbers, find the K-th missing number
starting from the leftmost number of the array.
Example 1:
Input: A = [4,7,9,10], K = 1
Output: 5
Explanation:
The first missing number is 5.
Example 2:
Input: A = [4,7,9,10], K = 3
Output: 8
Explanation:
The missing numbers are [5,6,8,...], hence the third missing number is 8.
Example 3:
Input: A = [1,2,4], K = 3
Output: 6
Explanation:
The missing numbers are [3,5,6,7,...], hence the third missing number is 6.
Note:
1 <= A.length <= 50000
1 <= A[i] <= 1e7
1 <= K <= 1e8
*/
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
const missingElement = function(nums, k) {
for (let i = 1, len = nums.length; i < len; i++) {
const dif = nums[i] - nums[i - 1] - 1
if (dif >= k) {
return nums[i - 1] + k
}
k -= dif
}
return nums[nums.length - 1] + k
}
// another
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
const missingElement = function(nums, k) {
const n = nums.length
let l = 0
let h = n - 1
const missingNum = nums[n - 1] - nums[0] + 1 - n
if (missingNum < k) {
return nums[n - 1] + k - missingNum
}
while (l < h - 1) {
const m = l + ((h - l) >> 1)
const missing = nums[m] - nums[l] - (m - l)
if (missing >= k) {
h = m
} else {
k -= missing
l = m
}
}
return nums[l] + k
}
// another
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
const missingElement = function(nums, k) {
const n = nums.length
if (k > missing(nums, n - 1)) return nums[n - 1] + k - missing(nums, n - 1)
let left = 0,
right = n - 1,
pivot
while (left < right) {
pivot = left + Math.floor((right - left) / 2)
if (missing(nums, pivot) < k) left = pivot + 1
else right = pivot
}
return nums[left - 1] + k - missing(nums, left - 1)
}
function missing(arr, idx) {
return arr[idx] - arr[0] - idx
}