leetcode-33.Search in Rotated Sorted Array 搜尋旋轉排序陣列
阿新 • • 發佈:2019-01-01
題目:
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., You are given a target value to search. If found in the array return its index, otherwise return You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). Example 1: Input: nums = [ Example 2: Input: nums = [ |
假設按照升序排序的陣列在預先未知的某個點上進行了旋轉。 ( 例如,陣列 搜尋一個給定的目標值,如果陣列中存在這個目標值,則返回它的索引,否則返回 你可以假設陣列中不存在重複的元素。 你的演算法時間複雜度必須是 O(log n) 級別。 示例 1: 輸入: nums = [ 示例 2: 輸入: nums = [ |
思路:排序陣列首先考慮使用二分查詢。兩種劃分,第一種nums[mid]<nums[j],說明後面是有序的,看target是否在這一區間,如果在i=mid+1,不在j=mid-1就在左邊找。第二種,nums[mid]>num[j],說明mid前面是有序,看target是否在這一區間,如果在j=mid-1,不在i=mid+1
class Solution {
public:
int search(vector<int>& nums, int target) {
int i=0,j=nums.size()-1,mid;
while(i<=j)
{
mid = (i+j)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]<nums[j])
{
if(nums[mid]<target && target<=nums[j]) i=mid+1;
else j=mid-1;
}else
{
if(nums[i]<=target && target<nums[mid]) j=mid-1;
else i=mid+1;
}
}return -1;
}
};