Total Accepted: 50992
Total Submissions: 162671
Difficulty: Medium
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.
Subscribe to see which companies asked this question
这个题目我想了好久才过的,本身循环排序数据就不是很好做。这个由于有重复数,所以当重复数是最前面和最后面的时候需要进行递归。
public class Solution {
public boolean search(int[] nums, int target) {
return search(nums, target, 0, nums.length-1);
}
public boolean search(int[] nums, int target,int m,int n) {
if(m>n)return false;
if(m<0||n>=nums.length)return false;
int i=m;int j=n;
if(nums[m]==target)return true;
while(i<=j){
int mid = (i+j)/2;
if(nums[mid]==target){
return true;
}
else{
if(nums[mid]<target){
if(nums[mid]>nums[m]){
i=mid+1;
}
else{
if(nums[mid]<nums[m]){
if(target<nums[m]){
i=mid+1;
}
else{
j=mid-1;
}
}
else{
if(search(nums, target, m+1, mid-1)||search(nums, target, mid+1, n)){
return true;
}
else{
return false;
}
}
}
}
else{
if(nums[mid]<nums[m]){
j=mid-1;
}
else{
if(nums[mid]>nums[m]){
if(target>nums[m]){
j=mid-1;
}
else{
i=mid+1;
}
}
else{
if(search(nums, target, m+1, mid-1)||search(nums, target, mid+1, n)){
return true;
}
else{
return false;
}
}
}
}
}
}
return false;
}
}
这是一个关于LeetCode中'搜索旋转排序数组II'问题的讨论。由于数组可能存在重复元素,这增加了查找目标的复杂性。当重复元素位于数组边界时,可能需要使用递归策略来解决。此问题要求编写一个函数来判断目标值是否存在于数组中。
432

被折叠的 条评论
为什么被折叠?



