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

    Question:

    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.

    Solution:

     1 class Solution {
     2 public:
     3     int search(vector<int>& nums, int target) {
     4                 int left=0;
     5     int right=nums.size()-1;
     6     if(left==right && nums[left]==target)
     7         return left;
     8     while(left!=right)
     9     {
    10         int mid=(left+right)/2;
    11         if(nums[mid]==target) return mid;
    12         if(nums[left]<=nums[mid])
    13         {
    14             if(nums[left]<=target && target<=nums[mid])
    15                 right=mid;
    16             else
    17                 left=mid+1;
    18         }
    19         else
    20         {
    21             if(nums[mid]<=target && target<=nums[right])
    22                 left=mid+1;
    23             else
    24                 right=mid;
    25         }
    26         if(left==right && nums[left]==target)
    27             return left;
    28     }
    29     return -1;
    30         
    31     }
    32 };

  • 相关阅读:
    Python的logging模块
    Python中的json模块
    Python的re模块
    NoSQL简介
    单例设计模式
    基于配置文件的方式配置AOP
    重用切点表达式
    切面优先级
    返回通知、异常通知、环绕通知
    后置通知
  • 原文地址:https://www.cnblogs.com/riden/p/4631415.html
Copyright © 2011-2022 走看看