标签:pre 指针 cat end sort dex tput class complex
Suppose an array sorted in ascending order 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.
Your algorithm‘s runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2]
, target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2]
, target = 3
Output: -1
解法一:我的解法 指针移动查找 但是可能不符合O(logN)
class Solution { public int search(int[] nums, int target) { int i = 0; int l = nums.length; if(l == 0) return -1; if(l == 1 && target != nums[0]) return -1; if(target == nums[0]) return 0; else if(target > nums[0]) { i++; while(i < l && nums[i-1] <= nums[i]){ if(target == nums[i]) return i; i++; } if(i < l && target == nums[i]) return i; }else if(target < nums[0]) { i = l - 1; while(i > 0 && nums[i-1] <= nums[i]) { if(target == nums[i]) return i; i--; } if(i >= 0 && target == nums[i]) return i; } return -1; } }
解法二:binary search
public int search(int[] A, int target) { int lo = 0; int hi = A.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (A[mid] == target) return mid; if (A[lo] <= A[mid]) { if (target >= A[lo] && target < A[mid]) { hi = mid - 1; } else { lo = mid + 1; } } else { if (target > A[mid] && target <= A[hi]) { lo = mid + 1; } else { hi = mid - 1; } } } return A[lo] == target ? lo : -1; }
leetcode 33. Search in Rotated Sorted Array
标签:pre 指针 cat end sort dex tput class complex
原文地址:https://www.cnblogs.com/jamieliu/p/10409261.html