Python version bsearch- 50 ms- how can this be faster?


  • 0
    Q
    def findPeakElement(self, num):
        if num:
        	if len(num) == 1:
        		return 0
        	elif len(num) == 2:
        		if num[0] > num[1]: return 0
        		else: return 1
        	else:
        		l = 0
        		r = len(num)-1
        		while (l < r):
        			mid = (l+r)/2
        			if num[mid] > num[mid-1] and num[mid] > num[mid+1]:
        				return mid
        			elif num[mid] < num[mid-1]:
        				r = mid
        			else:
        				l = mid+1
        	    
                if num[0] > num[len(num)-1]: return 0
                else: return len(num)-1
        else:
        	return 0

  • 0
    W

    Question, I am not sure if len(nums) would be the O(n)?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.