首页 > 代码库 > leetcode 二分查找 Search in Rotated Sorted ArrayII
leetcode 二分查找 Search in Rotated Sorted ArrayII
Search in Rotated Sorted Array II
Total Accepted: 18500 Total Submissions: 59945My SubmissionsFollow 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.
题意:一个已经排序好的数组,被按某个位置旋转了一次,给定一个值target,在该旋转后的数组里查找该值。(数组中的元素可能重复)
思路:二分查找
难点在于确定往数组的哪一半段继续二分查找
设起点、中间点、终点分别为 start、middle、end (采用前闭后开的区间表示方法
如果target = A[middle] return middle
如果A[middle] > A[start],则[start,middle)单调递增
1.如果target < A[middle] && target >= A[start],则 end = middle
2.start = middle + 1, otherwise
如果A[middle] < A[start],则[middle,end)单调递增
1.如果target > A[middle] && target <= A[end - 1],则 start = middle + 1
2.end = middle, otherwise
如果A[middle] == A[start],那A[start]也不会是target,可以通过start++; 去掉A[start]
复杂度:时间O(n),空间O(1)
int search(int A[], int n, int target){ int start = 0, end = n, middle ; while(start < end){ middle = (start + end) / 2; if(A[middle] == target) return middle; if(A[middle] > A[start]){ if(target >= A[start] && target < A[middle]){ end = middle; }else{ start = middle + 1; } }else if(A[middle] < A[start]){ if(target > A[middle] && target <= A[end - 1]){ start = middle + 1; }else{ end = middle; } } else{ ++start; } } return -1; }
leetcode 二分查找 Search in Rotated Sorted ArrayII
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。