Skip to content

Commit 06841cb

Browse files
committed
D. J.:
- Added leetcode problem and solution for 189 Rotate Array
1 parent 6fab9b8 commit 06841cb

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
1111
- [121 Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)
1212
- [122 Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/)
1313
- [169 Majority Element](https://leetcode.com/problems/majority-element/description/)
14+
- [189 Rotate Array](https://leetcode.com/problems/rotate-array/description/)
1415

1516
## Development 🔧
1617

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def rotate(self, nums: List[int], k: int) -> None:
6+
"""
7+
Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
8+
"""
9+
10+
def rev(left: int, right: int):
11+
while left < right:
12+
nums[left], nums[right] = nums[right], nums[left]
13+
left += 1
14+
right -= 1
15+
16+
k = k % len(nums)
17+
rev(0, len(nums) - 1)
18+
rev(0, k - 1)
19+
rev(k, len(nums) - 1)

tests/test_189_rotate_array.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._189_rotate_array import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "k", "expected"],
10+
argvalues=[
11+
([1, 2, 3, 4, 5, 6, 7], 3, [5, 6, 7, 1, 2, 3, 4]),
12+
([-1, -100, 3, 99], 2, [3, 99, -1, -100]),
13+
],
14+
)
15+
def test_func(nums: List[int], k: int, expected: int):
16+
Solution().rotate(nums, k)
17+
assert nums == expected

0 commit comments

Comments
 (0)