zoukankan      html  css  js  c++  java
  • Search in Rotated Sorted Array [LeetCode]

    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.

    Summary: Binary search can apply to a rotated sorted array, just by analysis of its property.

     1 class Solution {
     2 public:
     3     int search(int A[], int n, int target) {
     4         if(n == 0)
     5             return -1;
     6         if(n == 1) {
     7             if(A[0] == target)
     8                 return 0;
     9             else
    10                 return -1;
    11         }
    12         
    13         int median = n / 2;
    14         if(A[median] == target)
    15             return median;
    16             
    17         if(A[0] < A[median] && target >= A[0] && target < A[median] ||
    18             (A[0] > A[median] && (target >= A[0] || target < A[median]))){
    19             return search(A, median, target);
    20         }else{
    21             if(median + 1 >= n)
    22                 return -1;
    23             else{
    24                 int ret =  search(A + median + 1, n - median -1, target);
    25                 if(ret == -1)
    26                     return -1;
    27                 else 
    28                     return median + 1 + ret;
    29             }
    30         }
    31     }
    32 };
  • 相关阅读:
    站立会议02(冲刺2)
    站立会议01(冲刺2)
    测试计划
    cnblogs.com用户体验
    对其他组所提建议的回复(第一阶段)
    对各个小组的评论和一些建议
    团队会议第十天
    团队绩效评估规划
    团队会议第九天
    每日scrum(1)
  • 原文地址:https://www.cnblogs.com/guyufei/p/3408307.html
Copyright © 2011-2022 走看看