Skip to content

Commit

Permalink
Add new binary search example using go
Browse files Browse the repository at this point in the history
  • Loading branch information
joffilyfe committed Jan 4, 2024
1 parent 371ee43 commit 3013b1d
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
39 changes: 39 additions & 0 deletions golang/1539.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package golang

func binarySearch1539(arr []int, target int, size int) int {
left, right := 0, size - 1

for left <= right {
middle := (left + right) / 2

if arr[middle] == target {
return target
} else if target > arr[middle] {
left = middle + 1
} else if target < arr[middle] {
right = middle - 1
}
}

return -1
}

func findKthPositive(arr []int, k int) int {

count := 0
size := len(arr)

for i := 1; i <= arr[size - 1]; i++ {
result := binarySearch1539(arr, i, size)

if result == -1 {
count++

if count == k {
return i
}
}
}

return arr[size - 1] + (k - count)
}
27 changes: 27 additions & 0 deletions golang/1539_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package golang

import "testing"

func TestFirstFindKthPositive(t *testing.T) {
arr := []int{2,3,4,7,11}
k := 5

result := findKthPositive(arr, k)
expected := 9

if result != expected {
t.Fatalf("findKthPositive(%v, %v) = %v but expected %v", arr, k, result, expected)
}
}

func TestSecondFindKthPositive(t *testing.T) {
arr := []int{1,2,3,4}
k := 2

result := findKthPositive(arr, k)
expected := 6

if result != expected {
t.Fatalf("findKthPositive(%v, %v) = %v but expected %v", arr, k, result, expected)
}
}
1 change: 1 addition & 0 deletions golang/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
| -------------- | ------------- | ------------------------------------------------------------------------------------ |
| 888.go | Hash table | https://leetcode.com/problems/fair-candy-swap |
| 1608.go | Binary Search | https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/ |
| 1539.go | Binary Search | https://leetcode.com/problems/kth-missing-positive-number/ |

0 comments on commit 3013b1d

Please sign in to comment.