[Leetcode] [Python]34:search for a Range

Source: Internet
Author: User

#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '

34:search for a Range
https://oj.leetcode.com/problems/search-for-a-range/

Given a sorted array of integers, find the starting and ending position of a Given target value.
Your algorithm ' s runtime complexity must is in the order of O (log n).
If the target is not a found in the array, return [-1,-1].
For example,
Given [5, 7, 7, 8, 8, ten] and target value 8,
return [3, 4].

===comments by dabay===
Two-point lookup.
When Target is in the middle, expand toward both sides.
‘‘‘

Class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return A list of length 2, [Index1, Index2]
def searchrange (self, A, target):
def expend (Nums, index):
left = right = Index
While left-1 >= 0 and nums[left-1] = = Nums[index]:
Left-= 1
While right + 1 < len (nums) and Nums[right + 1] = = Nums[index]:
Right + = 1
return [left, right]

L, r = 0, Len (A)-1
While L <= r:
m = (L + r)/2
If a[m] = = target:
Return expend (A, M)
Elif A[m] < target:
L = m + 1
Else
r = M-1
Else
return [-1,-1]


def main ():
Sol = solution ()
Nums = [2,2]
target = 2
Print Sol.searchrange (nums, Target)


if __name__ = = ' __main__ ':
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)

[Leetcode] [Python]34:search for a Range

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.