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

325人阅读 评论(0)

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;
}
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：31722次
• 积分：679
• 等级：
• 排名：千里之外
• 原创：34篇
• 转载：11篇
• 译文：0篇
• 评论：9条
文章分类
评论排行
最新评论