https://leetcode.com/problems/search-in-rotated-sorted-array/description/

 

Search in Rotated Sorted Array - LeetCode

Can you solve this real interview question? Search in Rotated Sorted Array - There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly left rotated at an unknown index k (1 <=

leetcode.com

 

배열에서 타겟의 값을 찾는 문제이다. 특이점으로는 배열이 정렬되어있으나 해당 정렬은 왼쪽으로 회전 되어있을 수 있다는 점이다.

 

사실 문제 요구 사항으로 O(log n) 시간 복잡도를 요구하나 단순 for문(시간 복자도 O(n))으로 찾아도 문제가 통과된다. 하지만 알고리즘 연습을 위해 푸는 문제이니 정석적인 방법으로 풀었다.
O(log n)의 시간 복잡도를 요구한다는 것은 이진 탐색 알고리즘을 사용하라는 것으로 이해하면 된다.

 

단 조건이 회전된 배열일 수 있으므로 조건을 더 세분화 하여야 한다.
우선 이진탐색을 위해 left, right, mid 를 선정한 이후 조건을 세분화하여 left, right 의 값을 변화시키며 이진 탐색을 하여 해결하였다. 조건 선정에 자꾸 실패하여 꽤나 고생했다. 아래는 최종적으로 통과한 코드이다.

 

mid를 중심으로 왼쪽 또는 오른쪽은 신뢰할 수 있게 정렬 되어있다는 점을 이용하여 조건을 나누었다.

public class Solution {  
    public int search(int[] nums, int target) {  
        int left = 0;  
        int right = nums.length - 1;  
        while(left <= right){  
            int mid = (left + right) / 2;  
            int s = nums[left];  
            int e = nums[right];  
            int cur = nums[mid];  
  
            if(target == cur){  
                return mid;  
            }  
  
            if(cur >= s){  
                // 왼쪽이 정렬되어있을 경우  
                if(target > cur){  
                    left = mid + 1;  
                }else if(target >= s){  
                    right = mid - 1;  
                }else{  
                    left = mid + 1;  
                }  
            }else{  
                // 오른쪽이 정렬되어있을 경우  
                if(target < cur){  
                    right = mid - 1;  
                }else if(target <= e){  
                    left = mid + 1;  
                }else{  
                    right = mid - 1;  
                }  
            }  
        }  
  
        return -1;  
    }  
}

 

'Algolithm-Leetcode > Binary Search' 카테고리의 다른 글

Median of Two Sorted Arrays  (0) 2026.08.24
Koko Eating Bananas  (0) 2026.08.21
Find Minimum in Rotated Sorted Array  (0) 2026.08.14
Binary Search  (0) 2026.07.27

https://leetcode.com/problems/binary-search/description/

 

Binary Search - LeetCode

Can you solve this real interview question? Binary Search - Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

leetcode.com

 

이진탐색 알고리즘을 알고있는지 체크하는 문제로 O(log n) 시간복잡도를 요구한다.
특이점으로는 존재하지 않는 값을 타겟으로 하는 문제가 존재하고 그럴경우 -1 값을 리턴해야 한다는 것이다.

이진 탐색을 위해 low, high 값을 설정하고 mid를 인덱스로 하여 값을 비교하고, 값에 따라 low, high 미드값을 변경하여 mid 인덱스로 타겟을 찾아가는 방식이다

class Solution {  
    public int search(int[] nums, int target) {  
        int len = nums.length;  
        int low = 0;  
        int high = len - 1;  
        int mid = (low + high) / 2;  
  
        // while 의 조건문을 통해 타겟에 도달했는지 확인  
        while(nums[mid] != target){  
            int cur = nums[mid];  
            if(cur > target){  
                // index 범위를 초과하거나, 답이 없거나를 체크  
                if(mid - 1 < 0 || nums[mid - 1] < target){  
                    mid = -1;  
                    break;  
                }  
                // 중간점 체크를 위해 값 비교를 통해, low - high 값 전환  
                high = mid - 1;  
  
            }else{  
                // index 범위를 초과하거나, 답이 없거나를 체크  
                if(mid + 1 >= nums.length || nums[mid + 1] > target){  
                    mid = -1;  
                    break;  
                }  
  
                // 중간점 체크를 위해 값 비교를 통해, low - high 값 전환  
                low = mid + 1;  
            }  
            // 변경된 low, high 값을 이용해 새로운 중간점 변경  
            mid = (high + low) / 2;  
        }  
  
        return mid;  
    }  
}

 

답이 없는 부분을 체크하기 위해, 바로 근처 값을 확인 하는 방식을 넣었다.

이 때 인덱스가 배열의 범위를 초과하는지 체크하지 않으면 배열의 범위를 초과하는 인덱스 값을 검사하여

오류를 발생 시킬 수 있다.

 

이진 탐색 문제를 풀 때는 항상 범위를 잘못 처리하거나,

인덱스 조정 시 실수하여 while문을 탈출하지 못하는 실수를 할 때가 많다.

다행히 해당 문제는 조건이 까다롭지 않고 기초적인 이진탐색을 요구하기에 이진탐색을 입문하기 좋은 문제였다.

'Algolithm-Leetcode > Binary Search' 카테고리의 다른 글

Median of Two Sorted Arrays  (0) 2026.08.24
Koko Eating Bananas  (0) 2026.08.21
Find Minimum in Rotated Sorted Array  (0) 2026.08.14
Search in Rotated Sorted Array  (0) 2026.08.09

+ Recent posts