Tuesday, June 10, 2014

Leetcode: Search in Rotated Sorted Array II

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.

Solution:

In this example, we cannot do any better than $O(n)$ as we can have $n-1$ identical elements and the other being the target. In this case the target could be in any position. Hence, traversing the array is the best we can do.

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