题目链接: https://leetcode.com/problems/search-in-rotated-sorted-array/
1. 题目介绍()There is an integer array nums sorted in ascending order (with distinct values).
【Translate】: 有一个按升序(具有不同的值)排序的整数数组nums。
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
【Translate】: 在传递给你的函数之前,nums可能是在未知的枢轴索引k(1 <= k Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. 【Translate】: 给定可能的旋转后的数组nums和一个整数目标,如果target在nums中,则返回其索引,如果不在nums中,则返回-1。 You must write an algorithm with O(log n) runtime complexity. 【Translate】: 你必须写一个运行复杂度为O(log n)的算法。 【测试用例】: 这一题很简单,但是难点在于如何以O(log n)来实现。 nagthane所提供的题解 0ms 100% faster O(log(n)) binary search easy with explaination in comments,和jerry13466所提出的Revised Binary Search几乎一致。
【约束】:
public int search(int[] nums, int target) {
for (int i = 0; i < nums.length; i++)
{
if (nums[i] == target) return i;
}
return -1;
}
2.2 Binary Search – O(log n)
public int search(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int l = 0;
int r = nums.length - 1;
while(l



