leetcode [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,0,1,2,2,5,6]
might become [2,5,6,0,0,1,2]
).
You are given a target value to search. If found in the array return true
, otherwise return false
.
Example 1:
Input: nums = [2,5,6,0,0,1,2]
, target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2]
, target = 3
Output: false
Follow up:
- This is a follow up problem to Search in Rotated Sorted Array, where
nums
may contain duplicates. - Would this affect the run-time complexity? How and why?
题目大意:
在旋转数组中查找给定值,旋转数组是包含重复数字的。
解法:
我还是使用二分法进行查找,但是运行的效率很低。想起之前那个题不含重复值https://www.cnblogs.com/xiaobaituyun/p/10589908.html的效率同样也很低。
Java:
class Solution { private boolean searchCore(int[] nums, int target,int left,int right){ if(left>right) return false; int mid=(left+right)/2; if(nums[mid]==target) return true; if(nums[left]<nums[right] && (nums[left]>target||nums[right]<target)) return false; return searchCore(nums,target,left,mid-1)||searchCore(nums,target,mid+1,right); } public boolean search(int[] nums, int target) { if(nums.length==0) return false; return searchCore(nums,target,0,nums.length-1); } }
我的二分法总是通过函数的递归调用来实现,这样使用了很多栈空间。不推荐。
优化了一下代码,运行效率较低。
这种做法就是考虑划分数组时得到的数组前一半部分。前半部分只能有三种可能。
1.nums[start]=nums[mid],数组前半部分中存在重复值,需要跳过重复值。
2.nums[start]<nums[mid],数组前半部分是完全递增的。
3.nums[start]>nums[mid],数组分两部分递增
根据情况,对数组进行处理,再二分。
class Solution { public boolean search(int[] nums, int target) { int start=0,end=nums.length-1; while (start<=end){ int mid=(start+end)/2; if(nums[mid]==target) return true; if(nums[mid]==nums[start]) start++; else if(nums[mid]>nums[start]){ if(nums[mid]>target&&nums[start]<=target) end=mid-1; else start=mid+1; }else{ if(nums[mid]<target&&nums[end]>=target) start=mid+1; else end=mid-1; } } return false; } }