go: add «1608. Special Array With X Elements Greater Than or Equal X»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
0a97fc0356
commit
03dc69e6ed
1 changed files with 37 additions and 0 deletions
37
go/special-array-with-x-elements-greater-than-or-equal-x.go
Normal file
37
go/special-array-with-x-elements-greater-than-or-equal-x.go
Normal file
|
@ -0,0 +1,37 @@
|
||||||
|
package special_array_with_x_elements_greater_than_or_equal_x
|
||||||
|
|
||||||
|
import (
|
||||||
|
"slices"
|
||||||
|
)
|
||||||
|
|
||||||
|
func specialArray(nums []int) int {
|
||||||
|
bsearch := func(key int) int {
|
||||||
|
l := 0
|
||||||
|
r := len(nums) - 1
|
||||||
|
|
||||||
|
idx := len(nums)
|
||||||
|
for l <= r {
|
||||||
|
mid := (l + r) / 2
|
||||||
|
|
||||||
|
if nums[mid] >= key {
|
||||||
|
idx = mid
|
||||||
|
r = mid - 1
|
||||||
|
} else {
|
||||||
|
l = mid + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return idx
|
||||||
|
}
|
||||||
|
|
||||||
|
slices.Sort(nums)
|
||||||
|
for i, _ := range nums {
|
||||||
|
k := bsearch(i + 1)
|
||||||
|
|
||||||
|
if len(nums)-k == i+1 {
|
||||||
|
return i + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return -1
|
||||||
|
}
|
Loading…
Reference in a new issue