[CareerCup] 11.3 Search in Rotated Sorted Array 在旋转有序矩阵中搜索
2015-10-16 10:37
531 查看
11.3 Given a sorted array of n integers that has been rotated an unknown number of times, write code to find an element in the array. You may assume that the array was originally sorted in increasing order.
EXAMPLE
Input: find 5 in {15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14}
Output: 8 (the index of 5 in the array)
LeetCode上的原题,请参见我之前的博客Search in Rotated Sorted Array 在旋转有序数组中搜索和Search in Rotated Sorted Array II 在旋转有序数组中搜索之二。
EXAMPLE
Input: find 5 in {15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14}
Output: 8 (the index of 5 in the array)
LeetCode上的原题,请参见我之前的博客Search in Rotated Sorted Array 在旋转有序数组中搜索和Search in Rotated Sorted Array II 在旋转有序数组中搜索之二。
class Solution { public: int search(vector<int> nums, int target) { int left = 0, right = nums.size() - 1; while (left <= right) { int mid = left + (right - left ) / 2; if (nums[mid] == target) return mid; else if (nums[mid] < nums[right]) { if (nums[mid] < target && nums[right] >= target) left = mid + 1; else right = mid - 1; } else if (nums[mid] > nums[right]) { if (nums[left] <= target && nums[mid] > target) right = mid - 1; else left = mid + 1; } else --right; } return -1; } };
相关文章推荐
- 每天一个linux命令---telnet
- Nexus 5双清
- android 几个经常用到的字符串的截取
- Jenkins 安装及配置 1
- Core Animation系列之CADisplayLink
- css 设计与布局
- ajax请求--触发点击事件
- OpenStack Mnaila 2015-10-16 IRC会议内容
- FTP下载文件实例
- ResponseProcessCookies:121 - Cookie rejected问题
- ping检测整个网络的主机是否有响应
- Python的对象和类型
- 使用正则表达式NSRegularExpression 来验证textfiled输入的内容
- 快快快!27个提升效率的iOS开源库推荐
- linux下显示dd命令的进度:
- 本地化(基于系统语言)
- 如何在Linux上使用HAProxy配置HTTP负载均衡系统?
- Binary Tree Maximum Path Sum
- 堆和栈的区别
- 自定义UIPageControl小点的颜色