zoukankan      html  css  js  c++  java
  • 【LeetCode】033. Search in Rotated Sorted Array

    题目:

    Suppose an array sorted in ascending order 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 {
    public:
        int search(vector<int>& nums, int target) {
            int n = nums.size();
            if(n < 1)
                return -1;
            int begin = 0, end = n;
            while(begin < end){
                int mid = begin + (end - begin) / 2;
                if(nums[mid] == target)
                    return mid;
                if(nums[begin] <= nums[mid]){
                    if(nums[begin] <= target && target < nums[mid])
                        end = mid;
                    else
                        begin = mid + 1;
                } else {
                    if(nums[mid] < target && target <= nums[end - 1])
                        begin = mid + 1;
                    else
                        end = mid;
                }
            }
            return -1;
        }
    };

    Solution 2 

    class Solution {
    public:
        int search(vector<int>& nums, int target) {
            int n = nums.size();
            if(n < 1)
                return -1;
            int begin = 0, end = n - 1;
            while(begin < end){
                int mid = begin + (end - begin) / 2;
                if(nums[mid] > nums[end])
                    begin = mid + 1;
                else
                    end = mid;
            }
            int pivot = begin;
            begin = 0, end = n - 1;
            while(begin <= end){
                int mid = begin + (end - begin) / 2;
                int realmid = (mid + pivot) % n;
                if(nums[realmid] == target)
                    return realmid;
                else if(nums[realmid] < target)
                    begin = mid + 1;
                else
                    end = mid - 1;
            }
            return -1;
        }
    };
  • 相关阅读:
    截取图片组件
    node之mongodb的DAO
    模块化开发插件,组件
    tweenMax实体抛物线
    defineProperties属性的运用==数据绑定
    程序概述
    JavaBase
    [luogu 1092] 虫食算 (暴力搜索剪枝)
    [luogu1073 Noip2009] 最优贸易 (dp || SPFA+分层图)
    [51Nod 1218] 最长递增子序列 V2 (LIS)
  • 原文地址:https://www.cnblogs.com/Atanisi/p/7462335.html
Copyright © 2011-2022 走看看