版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/84918352
跟进“搜索旋转排序数组”,假如有重复元素又将如何?
是否会影响运行时间复杂度?
如何影响?
为何会影响?
写出一个函数判断给定的目标值是否出现在数组中。
样例
给出[3,4,4,5,7,0,1,2]和target=4,返回 true
解题思路:
只需要举出能够最坏情况的数据是 [1,1,1,1... 1] 里有一个0即可。在这种情况下是无法使用二分法的,复杂度是O(n) ,因此写个for循环最坏也是O(n),那就写个for循环就好了
public class Solution {
/**
* @param A: an integer ratated sorted array and duplicates are allowed
* @param target: An integer
* @return: a boolean
*/
public boolean search(int[] A, int target) {
// write your code here
for (int i = 0; i < A.length; i ++)
if (A[i] == target)
return true;
return false;
}
}