# LeetCode 33, Search in Rotated Sorted Array-----Binary Search

LeetCode 33, 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.

public class Solution {
public int search(int[] nums, int target) {
int len=nums.length;
int h=0, t=len-1,mid=-1;
while(mid!=(h+t)/2){
mid=(h+t)/2;
if(nums[mid]>=nums[h]){
if(target>=nums[h]&&target<=nums[mid])  t=mid;
else h=mid;
}else{
if(target<=nums[t] && target>nums[mid]) h=mid;
else t=mid;
}
}
if(nums[t]==target) return t;
return -1;
}
}

import java.util.*;
public class Solution {
public int search(int[] nums, int target) {
int len=nums.length;
if(len==0) return -1;
int h=0,t=len-1,mid=-1;
while(mid!=(h+t)/2){
mid=(h+t)/2;
if(nums[mid]<nums[h]) t=mid;
else h=mid;
}
int index=Arrays.binarySearch(nums,0,t,target);
if(index>=0) return index;
index=Arrays.binarySearch(nums,t,len,target);
if(index>=0) return index;
return -1;
}
}


• 本文已收录于以下专栏：

举报原因： 您举报文章：LeetCode 33, Search in Rotated Sorted Array-----Binary Search 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)