'Leetcode #35 Search Insert Position (list index out of range)
test=[]
for i in range(len(nums)):
if nums[i+1] > target > nums[i]:
test.append(nums[i])
test.append(target)
else:
test.append(nums[i])
return test.index(target)
I try to create new array sort the value first, then find the index of the target. It get error in index out of range in line nums[i+1]. How can I correct the code without the big change
Question link: https://leetcode.com/problems/search-insert-position/
Solution 1:[1]
What you are doing wrong:
This is because you are using nums[i+1] and since i is in the range 0 to len(nums) it gives index out of range for the last value of i.
You are checking if an element in nums is greater than the previous element or not. This will always be true because nums is sorted. I also don't know why are you appending the nums[i+1] and target to the test list. There's no need to create a new list.
What the question asks you to do
It tells you that the nums is sorted and you need to return the index if target is in nums. If not then return the index where it should be inserted. NOTE: It doesn't ask you to insert the target.
So, the steps which you can follow are:
- Loop through
nums. You can usefor i, num in enumerate(len(nums)):. This will give you the index i.e.iand the value of each element in nums i.e.num. - Take each element to check if the
targetis greater than or equal tonums[i]. - If it is then you need to return that index because that would be the index where the
targetneeds to be inserted. Eg: [1,3,6,8] iftargetis 5 then it should be inserted at 2 which is the index ofnums[i] > target. - If
targetis greater than the last element ofnumsthen return the last index ofnumsi.e.len(nums).
Combining all steps. The code we get(Do try it yourself first! Spoiler Alert!):
def searchInsert(self, nums: List[int], target: int) -> int:for i, num in enumerate(nums):if num >= target:return ireturn len(nums)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
