Search in Rotated Sorted Array

来源:互联网 发布:淘宝累计消费怎么看 编辑:程序博客网 时间:2024/05/16 23:50

  1. 首先我要在纸上,非常非常聪明且迅速且机灵,
  2. 给出几个用例,找出边界用例和特殊用例,确定特判条件;在编码前考虑到所有的条件
  3. 向面试官提问:问题规模,特殊用例
  4. 给出函数头
  5. 暴力解,简述,优化。
  6. 给出能够想到的最优价
  7. 伪代码,同时结合用例
  8. 真实代码
Search in Rotated Sorted Array

Suppose a sorted array 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.


http://collabedit.com/wutd3




bool in(vector<int> &arr, int l, int h, int x){    if(arr[l]<arr[h])        return x>=arr[l] && x<=arr[h];    else        return x>=arr[l] || x<=arr[h];}int search(vector<int> &arr, int x){    int l=0, h=arr.size();        while(l<h-1)    {        int m = l+(h-l)/2;                if(in(arr, l, m, x))            h=m;        else            l=m+1;    }    if(arr[l]==x) return l;    else return -1;}


修正版:

class Solution {public:    int search(int arr[], int n, int x)     {        int l=0, h=n-1;                while(l<h-1)        {            int m = l+(h-l)/2;                        if(in(arr, l, m, x))                h=m;            else                l=m+1;        }        if(arr[l]==x) return l;        if(arr[h]==x) return h;        else return -1;    }        bool in(int arr[], int l, int h, int x)    {    if(arr[l]<arr[h])        return x>=arr[l] && x<=arr[h];    else        return x>=arr[l] || x<=arr[h];    }};


原创粉丝点击