Skip to content

Commit

Permalink
add: original O(logn) solution for challenge3rotationcount
Browse files Browse the repository at this point in the history
  • Loading branch information
zhiwei-Feng committed May 16, 2021
1 parent 9353651 commit 7beb7fe
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package challenge3rotationcount

/*
Given an array of numbers which is sorted in ascending order and is rotated ‘k’ times around a pivot, find ‘k’.
You can assume that the array does not have any duplicates.
Input: [10, 15, 1, 3, 8]
Output: 2
Explanation: The array has been rotated 2 times.
Input: [4, 5, 7, 9, 10, -1, 2]
Output: 5
Explanation: The array has been rotated 5 times.
Input: [1, 3, 8, 10]
Output: 0
Explanation: The array has been not been rotated.
ref: https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/
*/

func countRotations(arr []int) int {
var (
start = 0
end = len(arr) - 1
)

for start < end {
mid := start + (end-start)/2
if mid < end && arr[mid] > arr[mid+1] {
return mid + 1
}
if mid > start && arr[mid-1] > arr[mid] {
return mid
}

if arr[start] < arr[mid] {
// left part sorted, so pivot is right part
start = mid + 1
} else {
end = mid - 1
}
}

return 0
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package challenge3rotationcount

import "testing"

func Test_countRotations(t *testing.T) {
type args struct {
arr []int
}
tests := []struct {
name string
args args
want int
}{
{"case1", args{[]int{10, 15, 1, 3, 8}}, 2},
{"case2", args{[]int{4, 5, 7, 9, 10, -1, 2}}, 5},
{"case3", args{[]int{1, 3, 8, 10}}, 0},
{"case4", args{[]int{10, 1, 3, 8, 9}}, 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := countRotations(tt.args.arr); got != tt.want {
t.Errorf("countRotations() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 7beb7fe

Please sign in to comment.