码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-04-23 20:59:07      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:[]   value   sts   --   log   turn   search   targe   div   

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

标签:[]   value   sts   --   log   turn   search   targe   div   

原文地址:https://www.cnblogs.com/Weixu-Liu/p/10758633.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!