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

mac2022-06-30  107

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[100000]; 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() == 0) return -1; for(int i = 0; i < nums.size(); i++){ p[i].num = nums[i]; p[i].index = i; } sort(p,p + nums.size(),cmp); int ans = Binary(p,0,nums.size() - 1,target); if(ans == -1) return -1; else return p[ans].index; } int Binary(points nums[],int left,int right,int target){ while(left <= right){ int mid = left + (right - left)/2; if(nums[mid].num == target) return mid; else if(nums[mid].num > target) right = mid - 1; else left = mid + 1; } return -1; } };

 

转载于:https://www.cnblogs.com/Weixu-Liu/p/10758633.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)