반응형
https://leetcode.com/problems/find-in-mountain-array/
Find in Mountain Array - LeetCode
Can you solve this real interview question? Find in Mountain Array - (This problem is an interactive problem.) You may recall that an array arr is a mountain array if and only if: * arr.length >= 3 * There exists some i with 0 < i < arr.length - 1 such tha
leetcode.com
MountainArray.get은 100회의 콜을 넘어가면 안됩니다.
mountrain array는 가장 큰 값을 기준으로 오름차순/내림차순 정렬되어있기 때문에, binary search를 이용하여 로그 시간에 해결할 수 있었습니다.
가장 큰 값을 찾아주고, 해당 값 기준 좌우측 범위에서 target을 탐색해줍니다.
class Solution {
public:
int findInMountainArray(int target, MountainArray &mountainArr) {
int m = findMid(mountainArr);
int res = bsearch(target, mountainArr, 0, m);
if (res != -1) {
return res;
}
return bsearchReverse(target, mountainArr, m + 1, mountainArr.length() - 1);
}
private:
int findMid(MountainArray &mountainArr) {
int s = 0, e = mountainArr.length() - 1;
while(s < e) {
int m = (s + e) / 2;
if(mountainArr.get(m) < mountainArr.get(m + 1)) {
s = m + 1;
} else {
e = m - 1;
}
}
return s;
}
int bsearch(int target, MountainArray &mountainArr, int s, int e) {
while(s <= e) {
int m = (s + e) / 2;
if(mountainArr.get(m) == target) return m;
else if(mountainArr.get(m) < target) s = m + 1;
else e = m - 1;
}
return -1;
}
int bsearchReverse(int target, MountainArray &mountainArr, int s, int e) {
while(s <= e) {
int m = (s + e) / 2;
if(mountainArr.get(m) == target) return m;
else if(mountainArr.get(m) > target) s = m + 1;
else e = m - 1;
}
return -1;
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 119. Pascal's Triangle II (0) | 2023.10.16 |
---|---|
LeetCode 1269. Number of Ways to Stay in the Same Place After Some Steps (0) | 2023.10.15 |
LeetCode 720. Longest Word in Dictionary (0) | 2023.10.09 |
LeetCode 34. Find First and Last Position of Element in Sorted Array (0) | 2023.10.09 |
LeetCode 1458. Max Dot Product of Two Subsequences (1) | 2023.10.08 |