Skip to content

Commit

Permalink
add 153
Browse files Browse the repository at this point in the history
  • Loading branch information
smart.cxj committed May 22, 2019
1 parent 46514bb commit d58598c
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
43 changes: 43 additions & 0 deletions leetcode/leetcode153/find_minimum_in_rotated_sorted_array.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package leetcode153

func findMin(nums []int) int {
if nums == nil || len(nums) == 0 {
return 0
}

low, high := 0, len(nums)-1

for low < high {
mid := low + (high-low)/2
if nums[mid] > nums[high] {
low = mid + 1
} else {
high = mid
}
}

return nums[low]
}

func findMinEarlyReturn(nums []int) int {
if nums == nil || len(nums) == 0 {
return 0
}

low, high := 0, len(nums)-1

for low < high {
if nums[low] < nums[high] {
return nums[low]
}

mid := low + (high-low)/2
if nums[mid] > nums[high] {
low = mid + 1
} else {
high = mid
}
}

return nums[low]
}
15 changes: 15 additions & 0 deletions leetcode/leetcode153/find_minimum_in_rotated_sorted_array_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package leetcode153

import "testing"

func TestFindMin(t *testing.T) {
type testFunc func([]int) int
testBody := func(f testFunc, t *testing.T) {
nums := []int{4, 5, 6, 7, 0, 1, 2}
if f(nums) != 0 {
t.Error("4, 5, 6, 7, 0, 1, 2 -> 0")
}
}
testBody(findMin, t)
testBody(findMinEarlyReturn, t)
}

0 comments on commit d58598c

Please sign in to comment.