problem:
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.
Array Binary Search
题意:对于一个有重复值的已序数组,先将其在某一个位置翻折,再用二分法寻找target是否在该数组中
thinking:
(1)出题人想考察二分法,但是该题的最简单的算法是遍历查找法,时间复杂度为O(n)
(2)回到二分法,再确定mid的左、右侧位置的位置时,考虑到有重复元素的出现,所以每次都要沿着mid往两遍遍历,时间复杂度最坏也可以达到O(n)
code:
遍历法:
class Solution {
public:
bool search(int A[], int n, int target) {
if(NULL == A || 0 == n)
return false;
for(int i = 0; i < n; ++i)
if(A[i] == target)
return true;
return false;
}
};
本文探讨了在具有重复元素的已排序数组中使用二分查找法进行目标值搜索的问题,分析了算法的时间复杂度变化,并提出优化策略。重点在于理解在存在重复值的情况下如何有效利用二分查找的效率,同时避免不必要的遍历,以实现最优的搜索性能。
522

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



