zoukankan      html  css  js  c++  java
  • LeetCode OJ--Search in Rotated Sorted Array

    http://oj.leetcode.com/problems/search-in-rotated-sorted-array/

    转换了一次的有序数组,进行类似二分查找。

    从begin到mid和从mid到end,二者中肯定有一个是有序的。

    #include <iostream>
    using namespace std;
      
    class Solution {
    public:
        int binarySearch(int A[],int target,int begin,int end)
        {
            int mid = (begin+end)/2;
    
            if(target == A[mid])
                return mid;
            if(target == A[begin])
                return begin;
            if(target == A[end])
                return end;
            if(begin>=end)
                return -1;
            
            if(A[begin]<A[mid])//前面有序
            {
                if(target>A[begin] && target<A[mid]) //在前面
                    return binarySearch(A,target,begin,mid-1);
                else
                    return binarySearch(A,target,mid+1,end); //在后面
            }
            else if(A[mid]<A[end])//后面有序
            {
                if(target>A[mid] && target<A[end]) //在后面
                    return binarySearch(A,target,mid+1,end);
                else
                    return binarySearch(A,target,begin,mid-1);//在前面
            }
            return -1;
        }
        int search(int A[], int n, int target) {
           return  binarySearch(A,target,0,n-1);
        }
    };
    
    int main() 
    {
        Solution myS;
        int A[] = {4,5,6,7,0,1,2};
        int ans = myS.search(A,7,0);
        cout<<ans<<endl;
        return 0;
    
    }
  • 相关阅读:
    linux基础命令之一
    Chrome 控制台使用大全
    移动端效果 — 页面引入在线视频
    移动端——简单计分表单
    JS操作cookie
    移动端页面字体——rem的使用
    Highcharts 使用总结
    CSS水平居中
    python学习 day2
    python学习 day1
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3546234.html
Copyright © 2011-2022 走看看