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

Posted weixu-liu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(二分查找 结构体) 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[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;
    }
};

 



以上是关于(二分查找 结构体) leetcode33. Search in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

leetcode(33)---搜索旋转排序数组(二分查找)

关于二分查找binary_search的结构体struct运用

二分查找(通过相对位置判断区间位置)--17--二分--LeetCode33搜索旋转排序数组

[LeetCode] 33. 搜索旋转排序数组 ☆☆☆(二分查找)

二分问题-LeetCode 3334(上下边界,二分查找)

LeetCode 33.搜索旋转排序数组