(二分查找 结构体) leetcode33. Search in Rotated Sorted Array

时间:2023-03-09 03:49:34
(二分查找 结构体) leetcode33. Search in Rotated Sorted Array

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

You are given a target value to search. If found in the array return its index, otherwise return -1.

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 = [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
--------------------------------------------------------------------------------
这个就是查找一个数的索引。查找的方法不限。我此处用的是二分查找。就是先用结构体保存数和它的索引,然后对于结构体进行排序,最后用二分查找。emmm,有点麻烦
C++代码:
struct points{
int num;
int index;
}p[];
inline bool cmp(points a,points b){
return a.num < b.num;
}
class Solution {
public:
int search(vector<int>& nums, int target) {
if(nums.size() == ) return -;
for(int i = ; i < nums.size(); i++){
p[i].num = nums[i];
p[i].index = i;
}
sort(p,p + nums.size(),cmp);
int ans = Binary(p,,nums.size() - ,target);
if(ans == -) return -;
else return p[ans].index;
}
int Binary(points nums[],int left,int right,int target){
while(left <= right){
int mid = left + (right - left)/;
if(nums[mid].num == target) return mid;
else if(nums[mid].num > target) right = mid - ;
else left = mid + ;
}
return -;
}
};