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;
        }
    };
    
  • 相关阅读:
    审核系统
    ehcache 缓存
    tomcat 内存设置
    html5 开发 跨平台 桌面应用
    service thread 结合使用
    html5桌面应用
    鼠标 事件
    服务器 判断 客户端 文件下载
    使用github管理Eclipse分布式项目开发
    uub代码
  • 原文地址:https://www.cnblogs.com/aiterator/p/6592088.html
Copyright © 2011-2022 走看看