Skip to content

Commit 04602ca

Browse files
二分法
1 parent 694d5ac commit 04602ca

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
'''
2+
Descripttion: 34. 在排序数组中查找元素的第一个和最后一个位置
3+
version: 1
4+
Author: Jason
5+
Date: 2020-12-01 16:12:21
6+
LastEditors: Jason
7+
LastEditTime: 2020-12-02 16:07:03
8+
'''
9+
10+
11+
from typing import List
12+
import random
13+
14+
15+
def GenerateRandomList(number, size):
16+
temp = list([0])
17+
random_legth = random.randint(0, size)
18+
current_length = 0
19+
while current_length < random_legth:
20+
temp.append(random.randint(1, number))
21+
current_length += 1
22+
return temp
23+
24+
25+
class Solution:
26+
def searchRange(self, nums: List[int], target: int) -> List[int]:
27+
length = len(nums)
28+
if length < 1:
29+
return [-1, -1]
30+
left = 0
31+
right = length - 1
32+
first_index = -1
33+
last_index = -1
34+
while left <= right:
35+
mid = left + ((right - left) >> 1)
36+
if nums[mid] == target:
37+
first_index = mid
38+
break
39+
elif nums[mid] > target:
40+
right = mid - 1
41+
else:
42+
left = mid + 1
43+
44+
if first_index == -1:
45+
return [-1, -1]
46+
# 向后找最大位置
47+
cur = first_index
48+
while cur < length and nums[cur] == target:
49+
last_index = cur
50+
cur += 1
51+
# 向前找最小位置
52+
cur = first_index
53+
while cur > -1 and nums[cur] == target:
54+
first_index = cur
55+
cur -= 1
56+
return [first_index, last_index]
57+
58+
def searchRange2(self, nums: List[int], target: int) -> List[int]:
59+
if target in nums:
60+
first_index = nums.index(target)
61+
last_index = nums[::-1].index(target)
62+
if (first_index + last_index + 1) == len(nums):
63+
return [first_index, first_index]
64+
return [first_index, len(nums) - 1 - last_index]
65+
return [-1, -1]
66+
67+
68+
s = Solution()
69+
for _ in range(10):
70+
li = GenerateRandomList(20, 20)
71+
index_random = random.randint(0, len(li) - 1)
72+
times_random = random.randint(1, 5)
73+
li.extend([li[index_random]] * times_random)
74+
target = li[index_random]
75+
li.sort()
76+
res = s.searchRange(li, target)
77+
res_stand = s.searchRange2(li, target)
78+
if res != res_stand:
79+
print(li)
80+
print(target)
81+
print("Wrong")
82+
print("Done")

0 commit comments

Comments
 (0)