본문 바로가기
LeetCode

[LeetCode] 33. Search in Rotated Sorted Array

by JungSeung 2023. 10. 31.
728x90

https://leetcode.com/

There is an integer array nums sorted in ascending order (with distinct values).

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums , or -1 if it is not in nums.

You must write an algorithm with O(log n) runtime complexity.


Example 1:

nput: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

 

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

 

Example 3:

Input: nums = [1], target = 0
Output: -1

 

Constraints:

  • 1 <= nums.length <= 5000
  • -10^4 <= nums[i] <= 10^4
  • All values of nums are unique.
  • nums is an ascending array that is possibly rotated.
  • -10^4 <= target <= 10^4

Code :

var search = function(nums, target) {
    let left = 0;
    let right = nums.length - 1;

    while (left <= right) {
        const mid = Math.floor((left + right) / 2);

        if (nums[mid] === target) {
            return mid;
        }

        if (nums[left] <= nums[mid]) {
            // 왼쪽 절반이 정렬되어 있는 경우
            if (nums[left] <= target && target < nums[mid]) {
                // 타겟이 왼쪽 절반에 속하는 경우
                right = mid - 1;
            } else {
                // 타겟이 오른쪽 절반에 속하는 경우
                left = mid + 1;
            }
        } else {
            // 오른쪽 절반이 정렬되어 있는 경우
            if (nums[mid] < target && target <= nums[right]) {
                // 타겟이 오른쪽 절반에 속하는 경우
                left = mid + 1;
            } else {
                // 타겟이 왼쪽 절반에 속하는 경우
                right = mid - 1;
            }
        }
    }

    return -1; // 타겟을 찾지 못한 경우
};

 

Solutions Code :

var search = function(nums, target) {
    let start = 0, end = nums.length - 1; // 시작과 끝 인덱스 초기화
    let mid = Math.floor((start + end) / 2); // 중간 인덱스 계산

    while (start <= end) { // 시작 인덱스가 끝 인덱스보다 작거나 같은 동안
        mid = Math.floor((start + end) / 2); // 중간 인덱스 업데이트

        if (target === nums[mid]) { // 중간 요소가 찾으려는 값인 경우
            return mid; // 중간 인덱스 반환
        }

        if (nums[start] <= nums[mid]) { // 시작 요소가 중간 요소보다 작거나 같은 경우
            if (nums[start] <= target && nums[mid] >= target) { // 시작부터 중간까지 범위에 타겟이 있는 경우
                end = mid - 1; // 끝 인덱스를 중간 - 1로 업데이트
            } else { // 그렇지 않은 경우
                start = mid + 1; // 시작 인덱스를 중간 + 1로 업데이트
            }
        } else { // 그렇지 않은 경우
            if (nums[end] >= target && nums[mid] <= target) { // 끝부터 중간까지 범위에 타겟이 있는 경우
                start = mid + 1; // 시작 인덱스를 중간 + 1로 업데이트
            } else { // 그렇지 않은 경우
                end = mid - 1; // 끝 인덱스를 중간 - 1로 업데이트
            }
        }
    }

    return -1; // 찾는 요소가 없는 경우 -1 반환
}

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90