题目链接:https://leetcode.com/problems/search-in-rotated-sorted-array/
题目:
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.
思路:
1、找到旋转点即第一个逆序,然后将数组分两半,分别用二分查找
2、二分查找 根据左右跟中间比较的结果 对有序的部分采用二分查找。
算法:
public int search(int[] nums, int target) { int left = 0,right = nums.length-1,mid = 0; while(left<=right){ mid = left+(right-left)/2; if(nums[mid]==target){ return mid; } if(nums[left]<nums[mid]){ //则left到mid有序 if(nums[left]==target){ return left; } if(nums[left]<=target&&target<nums[mid]){ //若target在left到mid之间 right = mid; }else{ left = mid + 1; } }else{//则mid到right之间有序 if(target==nums[right]){ return right; } if(nums[mid]<target&&target<=nums[right]){ //若target在mid到right之间 left = mid + 1; }else{ right = mid-1; } } } return -1; }
时间: 2024-10-15 06:51:04