File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
search-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ 풀이 :
3+ mid를 기준으로 왼쪽이 정렬된 경우, 오른쪽이 정렬된 경우를 나누고
4+ 정렬된 숫자 범위에 target값이 존재하느냐에 따라 범위를 이분 탐색으로 좁혀나간다
5+
6+ - 이분탐색 시 종료조건 및 비교조건에서 등호를 포함시킬지 여부 고려 필요
7+ while (left <= right) -> 탐색 범위에 양 끝 인덱스 포함
8+ -> left = mid + 1 또는 right = mid - 1 로 새로운 범위 업데이트
9+
10+ while (left < right) -> 탐색 범위에 오른쪽 끝 인덱스는 제외
11+ -> left = mid + 1 또는 right = mid 로 새로운 범위 업데이트
12+
13+ nums 개수 N
14+
15+ TC : O(logN)
16+ 이분 탐색으로 찾아서 log2N의 복잡도를 갖는다
17+
18+ SC : O(1)
19+ */
20+
21+ #include < vector>
22+ using namespace std ;
23+
24+ class Solution {
25+ public:
26+ int search (vector<int >& nums, int target) {
27+ int left = 0 , right = nums.size () - 1 ;
28+
29+ while (left <= right)
30+ {
31+ int mid = left + (right - left) / 2 ;
32+
33+ if (nums[mid] == target)
34+ return mid;
35+
36+ if (nums[left] <= nums[mid]) {
37+ if (nums[left] <= target && target < nums[mid])
38+ right = mid -1 ;
39+ else
40+ left = mid + 1 ;
41+ }
42+ else {
43+ if (nums[mid] < target && target <= nums[right])
44+ left = mid + 1 ;
45+ else
46+ right = mid - 1 ;
47+ }
48+ }
49+ return -1 ;
50+ }
51+ };
You can’t perform that action at this time.
0 commit comments