81. Search in Rotated Sorted Array II

来源:互联网 发布:电脑性能评估软件 编辑:程序博客网 时间:2024/06/11 01:22

81. Search in Rotated Sorted Array II

  • 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).

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

The array may contain duplicates.

  • 题目大意:给定一个旋转后的数组,写一个函数,判断给定的数,是否在数组中。

  • 思路:

    1. 直接遍历数组,判断是否有target,时间复杂度O(N)。
    2. 二分查找,查找目标数,时间复杂度O(logN).
  • 代码:

    package Array;/*** @Author OovEver* @Date 2017/11/28 10:10*/public class Solution {  public boolean search(int[] nums, int target) {      int start = 0, end = nums.length - 1, mid = -1;      while(start <= end) {          mid = (start + end) / 2;          if (nums[mid] == target) {              return true;          }          //If we know for sure right side is sorted or left side is unsorted          if (nums[mid] < nums[end] || nums[mid] < nums[start]) {              if (target > nums[mid] && target <= nums[end]) {                  start = mid + 1;              } else {                  end = mid - 1;              }              //If we know for sure left side is sorted or right side is unsorted          } else if (nums[mid] > nums[start] || nums[mid] > nums[end]) {              if (target < nums[mid] && target >= nums[start]) {                  end = mid - 1;              } else {                  start = mid + 1;              }              //If we get here, that means nums[start] == nums[mid] == nums[end], then shifting out              //any of the two sides won't change the result but can help remove duplicate from              //consideration, here we just use end-- but left++ works too          } else {//                low++也可以              end--;          }      }      return false;  }}

原创粉丝点击