码迷,mamicode.com
首页 > 其他好文 > 详细

33. Search in Rotated Sorted Array && 81. Search in Rotated Sorted Array II &&

时间:2016-07-24 08:13:26      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

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.

Hide Tags
 Binary Search Array
 
public class Solution {
  public int search(int[] nums, int target) {
    int len = nums.length;
    int leftMin = nums[0];
    int rightMax = nums[len - 1];

    if (target > rightMax && target < leftMin)
      return -1;
    boolean targetAtLeft = target >= leftMin;

    int left = 0;
    int right = len - 1;

    while (left <= right) {
      int mid = (left + right) / 2;
      int midVal = nums[mid];
      if (midVal == target)
        return mid;
      if (targetAtLeft) {
        if (midVal >= leftMin && midVal < target)
          left = mid + 1; // go right
        else
          right = mid - 1; //go left
      } else {
        if (midVal <= rightMax && midVal > target)
          right = mid - 1; // go left
        else
          left = mid + 1; //go right
      }
    }
    return -1;
  }
}

 

81. Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.

 
Hide Tags
 Array Binary Search
Hide Similar Problems
 (H) Search in Rotated Sorted Array
 

 

33. Search in Rotated Sorted Array && 81. Search in Rotated Sorted Array II &&

标签:

原文地址:http://www.cnblogs.com/neweracoding/p/5700052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!