Leetcode 81. Search in Rotated Sorted Array II

本文探讨了在允许重复元素的情况下,如何优化搜索旋转排序数组的算法。通过分析,了解允许重复元素如何影响运行时间复杂度,并提供了一个函数来确定目标是否存在于数组中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Analysis:
when the duplicate is allowed, so there is one condition that we do not know which is which part of this array is sorted.

public class Solution {
    public boolean search(int[] nums, int target) {
      int length = nums.length;
      if(length == 0)
        return false;
      return help(nums, target, 0, length - 1);
    }

    public boolean help(int[] nums, int target, int start, int end){
      if(start > end)
        return false;
      if(start == end)
      {
         if(nums[start] == target)
            return true;
          return false;
      }
      int mid = (start + end) / 2;
      if(nums[mid] == target)
        return true;

      //the logic
      // else if(nums[mid] < nums[end] && target > nums[mid])
      //   return help(nums, target, start + 1, end);

      //The first element before rotating is before the mid position
      if(nums[mid] < nums[end]){
         if(target < nums[mid])
            return help(nums, target, start, mid - 1);
         else if(target > nums[end])
            return help(nums, target, start, mid - 1);
          else
            return help(nums, target, mid + 1, end);
      }
      // the first element before rotating is exactely or after the mid position
      if(nums[mid] > nums[end]){
         if(target > nums[mid])
            return help(nums, target, mid + 1, end);
         else if(target < nums[start])
            return help(nums, target, mid + 1, end);
          else
            return help(nums, target, start , mid - 1);
      }
      if(nums[mid] == nums[end]){
        boolean temResult = help(nums, target, mid + 1, end);
        if(temResult)
          return temResult;
        else
          return help(nums, target, start, mid - 1);
      }
      return false;
    }
}