Skip to content

Commit 50cf53e

Browse files
committed
feat: solve #245 with python
1 parent 1a2d3f1 commit 50cf53e

File tree

1 file changed

+43
-0
lines changed
  • find-minimum-in-rotated-sorted-array

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
from typing import List
2+
from unittest import TestCase, main
3+
4+
5+
class Solution:
6+
def findMin(self, nums: List[int]) -> int:
7+
return self.solve_binary_search(nums)
8+
9+
"""
10+
Runtime: 32 ms (Beats 97.56%)
11+
Time Complexity: O(log n)
12+
- ํฌ๊ธฐ๊ฐ€ n์ธ ๋ฐฐ์—ด์— ๋Œ€ํ•œ ์ด๋ถ„ํƒ์ƒ‰์— O(log n)
13+
- while ์กฐ๊ฑด๋ฌธ ํŒ๋‹จ์— O(2), and ์—ฐ์‚ฐ์ด๋ฏ€๋กœ ๋‹จ์ถ• ํ‰๊ฐ€์— ์˜ํ•ด upper bound
14+
- ์—ฃ์ง€ ์ผ€์ด์Šค ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•œ ๋งˆ์ง€๋ง‰ lo, hi 2๊ฐœ ํ•ญ์— ๋Œ€ํ•œ min์—ฐ์‚ฐ์— O(2)
15+
> O(log n) * O(2) + O(2) ~= O(log n)
16+
17+
Memory: 16.82 (Beats 50.00%)
18+
Space Complexity: O(1)
19+
> ์ด๋ถ„ํƒ์ƒ‰์— ํ•„์š”ํ•œ ์ •์ˆ˜ํ˜• ๋ณ€์ˆ˜ lo, hi, mid 3๊ฐœ๋งŒ ์‚ฌ์šฉํ–ˆ์œผ๋ฏ€๋กœ n๊ณผ ์ƒ๊ด€์—†์ด O(1)
20+
"""
21+
def solve_binary_search(self, nums: List[int]) -> int:
22+
lo, hi = 0, len(nums) - 1
23+
while lo < hi and nums[hi] < nums[lo]:
24+
mid = (lo + hi) // 2
25+
if nums[lo] < nums[mid]:
26+
lo = mid
27+
elif nums[mid] < nums[hi]:
28+
hi = mid
29+
else:
30+
break
31+
32+
return min(nums[lo], nums[hi])
33+
34+
35+
class _LeetCodeTestCases(TestCase):
36+
def test_1(self):
37+
nums = [2, 1]
38+
output = 1
39+
self.assertEqual(Solution().findMin(nums), output)
40+
41+
42+
if __name__ == '__main__':
43+
main()

0 commit comments

Comments
ย (0)