Skip to content

Commit 448a036

Browse files
committed
feat: solve #246 in python
1 parent 3986165 commit 448a036

File tree

1 file changed

+67
-0
lines changed
  • search-in-rotated-sorted-array

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
from typing import List
2+
from unittest import TestCase, main
3+
4+
5+
class Solution:
6+
def search(self, nums: List[int], target: int) -> int:
7+
return self.solve_binary_search(nums, target)
8+
9+
"""
10+
Runtime: 4 ms (Beats 100.00%)
11+
Time Complexity: O(log n)
12+
> nums를 이진탐색으로 조회하므로 O(log n)
13+
14+
Memory: 17.03 MB (Beats 10.00%)
15+
Space Complexity: O(1)
16+
> index를 위한 정수형 변수만 사용하므로 O(1)
17+
"""
18+
def solve_binary_search(self, nums: List[int], target: int) -> int:
19+
lo, hi = 0, len(nums) - 1
20+
while lo < hi:
21+
mid = (lo + hi) // 2
22+
if nums[mid] == target:
23+
return mid
24+
25+
if nums[lo] <= nums[mid]:
26+
if nums[lo] <= target <= nums[mid]:
27+
hi = mid
28+
else:
29+
lo = mid + 1
30+
31+
else:
32+
if nums[mid] <= target <= nums[hi]:
33+
lo = mid + 1
34+
else:
35+
hi = mid
36+
37+
return lo if nums[lo] == target else -1
38+
39+
40+
class _LeetCodeTestCases(TestCase):
41+
def test_1(self):
42+
nums = [4,5,6,7,0,1,2]
43+
target = 0
44+
output = 4
45+
self.assertEqual(Solution.search(Solution(), nums, target), output)
46+
47+
def test_2(self):
48+
nums = [4,5,6,7,0,1,2]
49+
target = 3
50+
output = -1
51+
self.assertEqual(Solution.search(Solution(), nums, target), output)
52+
53+
def test_3(self):
54+
nums = [1]
55+
target = 0
56+
output = -1
57+
self.assertEqual(Solution.search(Solution(), nums, target), output)
58+
59+
def test_4(self):
60+
nums = [3, 1]
61+
target = 1
62+
output = 1
63+
self.assertEqual(Solution.search(Solution(), nums, target), output)
64+
65+
66+
if __name__ == '__main__':
67+
main()

0 commit comments

Comments
 (0)