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.
Idea: The worst time will O(n). For example, looking for 3 in two these two arrays:
[2, 3, 2, 2, 2, 2] ->mid=2, [2, 3, 2] [2, 2, 2]
[2, 2, 2, 2, 3, 2] ->mid=2, [2, 2, 2] [2, 3, 2].
When we compare the mid "2" with 3, we can not decide which half we should go to. So we need to search the two halves whatever. Since the best time complexity is O(n), we just do a left to right can.
Time: O(n) Space: O(1)
Code:
public class Solution {
public boolean search(int[] A, int target) {
for(int i=0;i<A.length;i++)
if(A[i]==target)
return true;
return false;
}
}
No comments:
Post a Comment