File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
find-minimum-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 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 ()
You canโt perform that action at this time.
0 commit comments