Skip to content

Commit 5ba1877

Browse files
committed
find minimum in rotated sorted array solution
1 parent 2af5762 commit 5ba1877

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
[๋ฌธ์ œํ’€์ด]
3+
- ์™ผ์ชฝ์˜ ์ˆ˜ ๋ณด๋‹ค ์˜ค๋ฅธ์ชฝ์˜ ์ˆ˜๊ฐ€ ์ž‘์€ ์ˆœ๊ฐ„์„ ์ฐพ์ž.
4+
- ๊ฐ€์žฅ ์™ผ์ชฝ์˜ ์ˆ˜ ๋ณด๋‹ค ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ์˜ ์ˆ˜๊ฐ€ ํฌ๋ฉด ํšŒ์ „์ด ์ผ์–ด๋‚˜์ง€ ์•Š์€ ์ƒํƒœ์ด๋ฏ€๋กœ, ์ฒซ๋ฒˆ์งธ๊ฐ€ ์ตœ์†Ÿ๊ฐ’์ด๋‹ค.
5+
- ํ’€์ด1
6+
time: O(N), space: O(1);
7+
class Solution {
8+
public int findMin(int[] nums) {
9+
if (nums.length == 1) {
10+
return nums[0];
11+
}
12+
13+
for (int i = 1; i < nums.length; i++) {
14+
if (nums[i - 1] > nums[i]) {
15+
return nums[i];
16+
}
17+
}
18+
return nums[0];
19+
}
20+
}
21+
- ํ’€์ด2 <์ด์ง„ํƒ์ƒ‰>
22+
time: O(log N), space: O(1)
23+
24+
[ํšŒ๊ณ ]
25+
์ด์ง„ํƒ์ƒ‰์œผ๋กœ ํ‘ธ๋Š” ๋Šฅ๋ ฅ์ด ๋ถ€์กฑํ•œ ๊ฒƒ ๊ฐ™๋‹ค.
26+
*/
27+
28+
class Solution {
29+
public int findMin(int[] nums) {
30+
int left = 0;
31+
int right = nums.length - 1;
32+
33+
if (nums[left] < nums[right]) {
34+
return nums[left];
35+
}
36+
37+
while (left < right) {
38+
int mid = (left + right) / 2;
39+
40+
if (nums[mid] <= nums[right]) {
41+
right = mid;
42+
} else {
43+
left = mid + 1;
44+
}
45+
}
46+
return nums[left];
47+
}
48+
}
49+

0 commit comments

Comments
ย (0)