Leetcode--34--Search for a Range

题型:binary search

关键在于二分查找中left,right,mid三者以及num[mid]与target的大小关系设置。

 

举例:nums = [1, 2, 2, 6, 7]         target = 2 或者 3

根据这个样例可以得出以下具体结果

 

首先,分4种情况:

1. 如果target存在nums中,得到>=target的最左位置

2. 如果target存在nums中,得到>=target的最右位置

3. 如果target不存在nums中,得到>target的最左位置

4. 如果target不存在nums中,得到>target的最右位置

 

#解决情况1, 4
#情况1:因为nums[mid]==target,r位置会向左移动
#情况4:因为return l,返回的l是如果对于target小于nums[mid]来说,l是会+1;否则r会-1,;不管怎样都是取的>target的位置
l = 0 r = len(nums) - 1 while l <= r: mid = l + (r - l) / 2 if nums[mid] == target: r = mid - 1 elif nums[mid] > target: r = mid - 1 else: l = mid + 1 return l

 

#解决情况2, 3
#理由同上
l = 0 r = len(nums) - 1 while l <= r: mid = l + (r - l) / 2 if nums[mid] == target: l = mid + 1 elif nums[mid] > target: r = mid - 1 else: l = mid + 1

 

 

solution code:

 1 class Solution(object):
 2     def searchRange(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         if len(nums)==0:
 9             return [-1,-1]
10         if nums[len(nums)-1] < target or nums[0] > target:
11             return [-1,-1]
12         l = 0
13         r = len(nums) - 1
14         # <= 
15         while l <= r:
16             mid = l + (r - l) / 2
17             if nums[mid] == target:
18                 r = mid - 1
19             elif nums[mid] > target:
20                 r = mid - 1
21             else:
22                 l = mid + 1
23         left = l
24         l = 0
25         r = len(nums) - 1
26         while l <= r:
27             mid = l + (r - l) / 2
28             if nums[mid] == target:
29                 l = mid + 1
30             elif nums[mid] > target:
31                 r = mid - 1
32             else:
33                 l = mid + 1
34         right = r
35         if nums[left] == target:
36             return [left, right]
37         else:
38             return [-1, -1]
39             #return [right, left]
View Code

 

你可能感兴趣的:(Leetcode--34--Search for a Range)