Skip to content

Commit 1810720

Browse files
add post '(Leetcode) 33 - Search in Rotated Sorted Array'
1 parent 844a7df commit 1810720

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

_posts/2024-06-03-leetcode-33.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
---
2+
layout: post
3+
title: (Leetcode) 33 - Search in Rotated Sorted Array
4+
categories: [스터디-알고리즘]
5+
tags:
6+
[자바, java, 리트코드, Leetcode, 알고리즘, algorithm, pointer, rotate, array]
7+
date: 2024-06-03 8:30:00 +0900
8+
toc: true
9+
---
10+
11+
기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.
12+
13+
[https://neetcode.io/practice](https://neetcode.io/practice)
14+
15+
---
16+
17+
[https://leetcode.com/problems/search-in-rotated-sorted-array/](https://leetcode.com/problems/search-in-rotated-sorted-array/)
18+
19+
## 내가 작성한 풀이
20+
21+
값을 발견하면 index를 반환하고, 아닐경우 -1을 반환한다.
22+
23+
```java
24+
class Solution {
25+
public int search(int[] nums, int target) {
26+
for(int i = 0 ; i < nums.length; i++) {
27+
if(nums[i] == target) {
28+
return i;
29+
}
30+
}
31+
return -1;
32+
}
33+
}
34+
```
35+
36+
### TC, SC
37+
38+
시간 복잡도는 O(n)이고, 공간 복잡도는 O(1)이다.
39+
40+
## 조금 더 최적화 하자면 (binary search)
41+
42+
문제에서 O(log n) 의 시간복잡도로 풀어보라고 제시하였다.
43+
44+
[(Leetcode) 153 - Find Minimum in Rotated Sorted Array](https://algorithm.jonghoonpark.com/2024/06/03/leetcode-153)
45+
바로 이전에 풀었던 문제와 비슷하게 접근하면 될 것으로 보인다.
46+
47+
- right가 mid보다 크다? → 오른쪽 부분은 제대로 정렬되어 있다
48+
- right가 mid보다 작다? → 왼쪽 부분은 제대로 정렬되어 있다.
49+
50+
이 두가지를 이용하면 된다.
51+
52+
```java
53+
public int search(int[] nums, int target) {
54+
int left = 0, right = nums.length - 1;
55+
while(left <= right) {
56+
int mid = left + (right - left) / 2;
57+
58+
if (nums[mid] == target) {
59+
return mid;
60+
}
61+
62+
if(nums[mid] < nums[right]) {
63+
if (target < nums[mid] || target > nums[right]) {
64+
right = mid - 1;
65+
} else {
66+
left = mid + 1;
67+
}
68+
} else {
69+
if (target < nums[left] || target > nums[mid]) {
70+
left = mid + 1;
71+
} else {
72+
right = mid - 1;
73+
}
74+
}
75+
}
76+
77+
return -1;
78+
}
79+
```
80+
81+
### TC, SC
82+
83+
시간 복잡도는 O(logn)이고, 공간 복잡도는 O(1)이다.

0 commit comments

Comments
 (0)