Look at the first for-loop:
for i in range(len(nums)):
if nums[i] == target:
left_index = i
break
else:
return [-1,-1]
When it's executing the for-loop for the first time, nums[i]
has a value of 3.
3 is not equal to 5 (your target), so it will execute the else statement and directly return [-1, -1]
.
If you now unindent the else
statement by one level, it will only be executed AFTER the for-loop has iterated over all numbers [reference]. If your target value is found, the break
keyword will prevent the else statement from getting executed.
So, the following would work:
for i in range(len(nums)):
if nums[i] == target:
left_index = i
break
else:
return [-1,-1]
Do NOT remove the else part, or you would get a NameError
for left_index
and right_index
if your target is not found in the numbers!
Add an else
statement to the second for loop, too (to avoid a NameError
for right_index
when target is not found a second time in nums):
nums = [3,4,5,5,5,6,7,8,9]
target = 5
class Solution:
def searchRange(self, nums, target):
for i in range(len(nums)):
if nums[i] == target:
left_index = i
break
else:
return [-1, -1]
for j in range(len(nums)-1, -1, -1):
if nums[j] == target:
right_index = j
break
else:
return [left_index, -1]
return [left_index, right_index]
x = Solution()
print(x.searchRange(nums, target))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…