33. Search in Rotated Sorted Array

**Description**Hints**Submissions**Solutions

Total Accepted: 168414
Total Submissions: 524192
Difficulty: Medium
Contributor: LeetCode

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.

Hide Company Tags
LinkedIn Bloomberg Uber Facebook Microsoft
Hide Tags
Binary Search Array
Hide Similar Problems
(M) Search in Rotated Sorted Array II (M) Find Minimum in Rotated Sorted Array

** 解题思路 **
Use Binary Search
The idea is that when rotating the array, there must be one half of the array that is still in sorted order.
For example, 6 7 1 2 3 4 5, the order is disrupted from the point between 7 and 1. So when doing binary search, we can make a judgement that which part is ordered and whether the target is in that range, if yes, continue the search in that half, if not continue in the other half.


    /*
     Use Binary Search
     The idea is that when rotating the array, there must be one half of the array that is still in sorted order.
     For example, 6 7 1 2 3 4 5, the order is disrupted from the point between 7 and 1. So when doing binary search, we can make a judgement that which part is ordered and whether the target is in that range, if yes, continue the search in that half, if not continue in the other half.
    */
    public int search(int[] nums, int target) {
      int start = 0, end = nums.length - 1;
      while (start <= end) {
          int mid = start + (end - start) /2 ;
          int val = nums[mid];
          if (val == target) {
              return mid;
          }
          
          if (nums[start] <= val) {
              if (target < val && target >= nums[start]) {
                  end = mid - 1;
              } else {
                  start = mid + 1;
              }
          } 
          
          if (val <= nums[end]) {
              if (target > val && target <= nums[end]) {
                  start = mid + 1;
              } else {
                  end = mid - 1;
              }
          }
      }
      return - 1;        
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容