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 e75eb3c commit 371ee43
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 3 deletions.
33 changes: 33 additions & 0 deletions golang/1608.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package golang

import "sort"

// binarySearch looks for the first element equal of immediate greater than target
func binarySearch(nums []int, target int) int {
left, right := 0, len(nums)-1

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

if nums[middle] >= target {
right = middle - 1
} else {
left = middle + 1
}
}

return len(nums) - left
}

func specialArray(nums []int) int {

sort.Ints(nums)

for i := 1; i <= len(nums); i++ {
if binarySearch(nums, i) == i {
return i
}
}

return -1
}
43 changes: 43 additions & 0 deletions golang/1608_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package golang

import "testing"

func TestSpecialArray(t *testing.T) {
nums := []int{3, 5, 1}
expected := 2
result := specialArray(nums)

if result != expected {
t.Fatalf(`specialArray(%#v) = %v != %v`, nums, result, expected)
}
}

func TestSecondSpecialArray(t *testing.T) {
nums := []int{1, 4, 5}
expected := 2
result := specialArray(nums)

if result != expected {
t.Fatalf(`specialArray(%#v) = %v != %v`, nums, result, expected)
}
}

func TestThirdSpecialArray(t *testing.T) {
nums := []int{0, 1}
expected := 1
result := specialArray(nums)

if result != expected {
t.Fatalf(`specialArray(%#v) = %v != %v`, nums, result, expected)
}
}

func TestFourthSpecialArray(t *testing.T) {
nums := []int{0, 0}
expected := -1
result := specialArray(nums)

if result != expected {
t.Fatalf(`specialArray(%#v) = %v != %v`, nums, result, expected)
}
}
7 changes: 4 additions & 3 deletions golang/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
| Problem Number | Tag | URL |
| -------------- | ---------- | --------------------------------------------- |
| 888.go | Hash table | https://leetcode.com/problems/fair-candy-swap |
| Problem Number | Tag | URL |
| -------------- | ------------- | ------------------------------------------------------------------------------------ |
| 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/ |

0 comments on commit 371ee43

Please sign in to comment.