-
Notifications
You must be signed in to change notification settings - Fork 32
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
Showing
2 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
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,16 @@ | ||
package day197 | ||
|
||
// RotateRightK rotates the nums slice in-place to the right. | ||
// Runs in O(N) time and O(1) space. | ||
func RotateRightK(nums []int, k int) { | ||
k %= len(nums) | ||
for i := 0; i < k/2; i++ { | ||
nums[i], nums[k-1-i] = nums[k-1-i], nums[i] | ||
} | ||
for i := 0; i < (len(nums)-k)/2; i++ { | ||
nums[k+i], nums[len(nums)-1-i] = nums[len(nums)-1-i], nums[k+i] | ||
} | ||
for i := 0; i < len(nums)/2; i++ { | ||
nums[i], nums[len(nums)-1-i] = nums[len(nums)-1-i], nums[i] | ||
} | ||
} |
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,34 @@ | ||
package day197 | ||
|
||
import ( | ||
"reflect" | ||
"testing" | ||
) | ||
|
||
var testcases = []struct { | ||
nums []int | ||
k int | ||
expected []int | ||
}{ | ||
{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 4, []int{5, 6, 7, 8, 9, 10, 1, 2, 3, 4}}, | ||
} | ||
|
||
func TestRotateRightK(t *testing.T) { | ||
t.Parallel() | ||
for _, tc := range testcases { | ||
result := append([]int{}, tc.nums...) | ||
RotateRightK(result, tc.k) | ||
if !reflect.DeepEqual(result, tc.expected) { | ||
t.Errorf("Expected %v, got %v", tc.expected, result) | ||
} | ||
} | ||
} | ||
|
||
func BenchmarkRotateRightK(b *testing.B) { | ||
for i := 0; i < b.N; i++ { | ||
for _, tc := range testcases { | ||
result := append([]int{}, tc.nums...) | ||
RotateRightK(result, tc.k) | ||
} | ||
} | ||
} |