-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
smart.cxj
committed
May 22, 2019
1 parent
46514bb
commit d58598c
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
43 changes: 43 additions & 0 deletions
43
leetcode/leetcode153/find_minimum_in_rotated_sorted_array.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
15
leetcode/leetcode153/find_minimum_in_rotated_sorted_array_test.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |