• (二分查找 结构体) 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;
        }
    };


  • 相关阅读:
    什么变量在堆内存里存放,什么变量在栈内存里存放
    iOS应用开发:什么是ARC?
    Stack栈 Heap堆
    iOS中四种实例变量的范围类型@private@protected@public@package
    [转载] iOS应用程序的生命周期
    总结iOS 8和Xcode 6的各种坑
    [转载]对iOS开发中内存管理的一点总结与理解
    企业账号申请以及打包上传
    更换AppleWWDRCA.cer证书
    iOS9适配
  • 原文地址:https://www.cnblogs.com/Weixu-Liu/p/10758633.html
Copyright © 2020-2023  润新知