LeetCode #33 Search in Rotated Sorted Array
2015-08-14 16:31
375 查看
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,
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.
(i.e.,
0 1 2 4 5 6 7might 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.
class Solution { private: int find_rotate_index(vector<int>& nums) { int left = 0, right = nums.size() - 1; while(left < right){ int mid = (left + right) >> 1; if(nums[mid] > nums[right]) left = mid + 1; else right = mid; } return left; } public: int search(vector<int>& nums, int target) { int rotate_index = find_rotate_index(nums); int left, right, last_index = nums.size() - 1; if(target > nums[last_index]) {left = 0; right = rotate_index - 1;} else if(target < nums[last_index]) {left = rotate_index; right = last_index - 1;} else return last_index; while(left <= right){ int mid = (left + right) >> 1; if(nums[mid] < target) left = mid + 1; else if(nums[mid] > target) right = mid - 1; else return mid; } return -1; } };
相关文章推荐
- 计算字符个数(java)
- SSL与TLS 区别 以及介绍
- 4个值得注意的点(先记后写)
- easydialog.js
- 如何能够在Android运行Java的main方法
- Luci上增加本地ipk软件包安装功能
- LA3987 Ladies’ Choice 婚姻稳定算法
- VS2015编译boost1.58 Linux平台编译
- 【JavaScript】DOM总结
- 获取 Iphone 手机信息
- Yandex.Algorithm Online Round 3 Sunday, June 15, 2014
- 在OpenResty中使用淘宝的concat进行css和js合并,同时支持GZIP静态压缩
- Android自定义View画曲线
- 一个不错的关于mysql和posgresql比较的帖子
- C++14系列(2):C/C++的时间函数
- PAT 1033. To Fill or Not to Fill (25)
- Leetcode 210 Course Schedule II 课程表II
- SQL当前的进程信息,当前的执行语句
- 验证签名
- AMD驱动安装