zoukankan      html  css  js  c++  java
  • 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.

    思路:


    二分法的变形,每次变换一共是三种情况,找出中间值,相等时最理想的情况;

    中间值大于最左边的数以及中间值在下面。

    对于第二种情况,考虑是不是左边的左边,然后就是right减去1;

    对于第三种情况,考虑最右边的右边,然后就是left加上1.

    好题目!!!

    代码:

    class Solution {
    public:
        int search(vector<int>& nums, int target) {
            int left=0,right=nums.size()-1;
            while(left<=right){
                int mid=(left+right)/2;
                if(nums[mid]==target)   return mid;
                if(nums[mid]>=nums[left]){
                    //在左边
                    if(target>=nums[left]&&target<nums[mid])   
                        right=mid-1;
                    else
                        left=mid+1;
                }else{
                    //在右边
                    if(target<=nums[right]&&nums[mid]<target)
                        left=mid+1;
                    else
                        right=mid-1;
                }
            }
            return -1;
        }
    };


  • 相关阅读:
    图形验证码---pillow
    vue富文本编辑器vue-quill-editor
    django邮件发送
    Django REST Framework JWT
    jwt验证
    使用django的用户表进行登录管理
    [转]CSRF漏洞详细说明
    Django框架10
    Django框架09
    Django框架08
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519829.html
Copyright © 2011-2022 走看看