LeetCode 33 Search in Rotated Sorted Array(在旋轉排序數組中搜索)(*)
翻譯
假定一個數組在一個我們預先不知道的軸點旋轉。
例如,0 1 2 4 5 6 7可能會變為4 5 6 7 0 1 2。
給你一個目標值去搜索,如果找到了則返回它的索引,否則返回-1。
你可以假定沒有重復的元素存在於數組中。
原文
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.
代碼
class Solution {
public:
int search(vector& nums, int target) {
int l = 0, r = nums.size()-1;
while (l<=r) {
int mid = (r-l)/2+l;
if (nums[mid] == target)
return mid;
if (nums[mid] < nums[r]) {
if (nums[mid]