Search in Rotated Sorted Array
来源:互联网 发布:淘宝精选是怎么报名 编辑:程序博客网 时间:2024/06/05 15:08
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.
(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 bs(vector<int>& nums, int st, int en, int target) { if(st > en) return -1; int m; while(st <= en) { m = st + (en - st)/2; if(nums[m] == target) { return m; } if(nums[m] < target) { st = m + 1; }else { en = m - 1; } } return -1; } int search(vector<int>& nums, int target) { int l = 0; int r = nums.size() - 1; int m; int pos = -1; if(nums[l] < nums[r]) { pos = 0; return bs(nums, 0, r, target); } while(l < r) { if(r - l == 1) { pos = l; break; } m = l + (r - l)/2; if(nums[m] > nums[l]) { l = m; }else if(nums < nums[r]) { r = m; } } int lpos = bs(nums, 0, pos - 1, target); int rpos = bs(nums, pos, nums.size() - 1, target); if(lpos >= 0) return lpos; if(rpos >= 0) return rpos; return -1; }};
0 0
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array
- 淘宝秒杀服务器架构猜想
- 图片旋转
- Caused by: groovy.lang.MissingPropertyException: No such property: ID for class
- tomcat
- win7下开启共享文件夹
- Search in Rotated Sorted Array
- Android翻译】关于Activity的onSaveInstanceState调用时机的说明
- 第一次写博客
- Junit4的使用(@Test @Before @After @BeforeClass @AfterClass @Ignore)
- intent
- 快速傅里叶反变换(一维)
- C#串口通讯(变参、委托、线程安全队列)
- Java栈的模拟实现
- cocos2dx[3.8] ——入口类AppDelegate.cpp