์๋ฐ ์ฝ๋
class Solution {
public int search(int[] nums, int target) {
int idx = findMin(nums);
int findL = findIdx(nums,0,idx-1,target);
int findR = findIdx(nums,idx,nums.length-1,target);
return Math.max(findL,findR);
}
public int findIdx(int[] nums,int left, int right,int target){
while(left<=right){
int mid = (left+right)/2;
if(nums[mid]==target){
return mid;
}else if(nums[mid]<target){
left = mid+1;
}else{
right = mid-1;
}
}
return -1;
}
public int findMin(int[] nums){
int left = 0;
int right = nums.length-1;
if (nums[left]<=nums[right]){
return 0;
}
while(left<right){
int mid = (left+right)/2;
if(nums[mid]>nums[right]){
left = mid+1;
}else{
right = mid;
}
}
return left;
}
}
ํ์ด์ฌ ์ฝ๋
class Solution(object):
def search(self, nums, target):
idx = self.findMin(nums)
findL = self.findIdx(nums,0,idx-1,target)
findR = self.findIdx(nums,idx,len(nums)-1,target)
return max(findL,findR)
def findIdx(self,nums,left,right,target):
while left<=right:
mid = (left+right)//2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid+1
else:
right = mid -1
return -1
def findMin(self,nums):
left = 0
right = len(nums)-1
if nums[left] <= nums[right]:
return 0;
while left<right:
mid = (left+right)//2
if nums[mid]>nums[right]:
left = mid+1
else:
right = mid
return left
์ด๋ถํ์์ผ๋ก ํ์ ๋์ด ์๋ ์ค๋ฆ์ฐจ์ ๋ฐฐ์ด์ ์ค๋ฆ์ฐจ์ ์ ๋ ฌ๋์ด์๋ 2๊ฐ์ ๋ฐฐ์ด๋ก ๋๋๋ค.
[4,5,6,7,0,1,2] ๋ฐฐ์ด์ด ์ฃผ์ด์ง๋ค๋ฉด
findMin() ํจ์๋
์ค๋ฆ์ฐจ์์ด ์์๋๋ ๊ฐ์ ์ธ๋ฑ์ค๋ฅผ ๊ตฌํ๋ ํจ์์ด๋ค.
์ฆ, 4๊ฐ ๋ฐํ๋ ๊ฒ์ด๋ค.
๊ทธ๋ ค๋ฉด ๊ทธ ์ธ๋ฑ์ค๋ฅผ ๊ธฐ์ค์ผ๋ก, [4,5,6,7] ๊ณผ [0,1,2] ๋ก ๋ถ๋ฆฌํ ์ ์๊ณ
์ค๋ฆ์ฐจ์ ๋์ด์๋ ๋ ๋ฐฐ์ด์์ target ๊ฐ์ ์ฐพ๊ธฐ ์ํ ์ด๋ถํ์์ ํ๋ฒ ๋ ํ๋ฉด ๋๋ค.