Tuesday, June 10, 2014

LeetCode (Python): 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.

class Solution:
    # @param A a list of integers
    # @param target an integer
    # @return a boolean
    def search(self, A, target):
        for i in xrange(0, len(A)):
            if A[i]==target:
                return True
        return False

No comments :

Post a Comment