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

    Subscribe to see which companies asked this question.

    一串有序数字,这串数字有可能前面一部分挪到后面了。 给你一个目标值, 求这个数字在这串数字中的位置。

    直接二分, 只不过需要事先判断一下就好了。

    class Solution {
    public:
        int search(vector<int>& nums, int target) {
            if(nums.size() == 0)
                return -1;
            int s = nums.size() - 1;
            int b = 0, e = s;
            if(target >= nums[0])
            {
                while(b < e)
                {
                    int mid = (b + e) / 2;
                    if(nums[mid] == target)
                        return mid;
                    else if(nums[mid] > target)
                        e = mid - 1;
                    else
                    {
                        if(nums[mid] < nums[0])
                            e = mid - 1;
                        else
                            b = mid + 1;
                    }
                }
            }
            else
            {
                while(b < e)
                {
                    int mid = (b + e)/2;
                    if(nums[mid] == target)
                        return mid;
                    else if(nums[mid] < target)
                        b = mid + 1;
                    else
                    {
                        if(nums[mid] < nums[0])
                            e = mid - 1;
                        else
                            b = mid + 1;
                    }
                }
            }
            if(nums[b] == target)
                return b;
            else
                return -1;
        }
    };
    
  • 相关阅读:
    Android语音识别功能使用
    Android 游戏开发必备的基础知识
    程序员需要具备的基本技能
    在IDEA上开发Android
    Eclipse中看java源代码
    Android高效开发:
    优秀程序员的十个习惯
    Android 自定义控件
    Android文件读写,保存数据
    java面试题(一)
  • 原文地址:https://www.cnblogs.com/aiterator/p/6592088.html
Copyright © 2011-2022 走看看