Search-35. Search Insert Position

daniel20030312

猪猪

Posted on September 29, 2024

Search-35. Search Insert Position

I did Search-35. Search Insert Position

Here is question:
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:

Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:

Input: nums = [1,3,5,6], target = 7
Output: 4

Code:

class Solution(object):
    def searchInsert(self, nums, target):
        index = 0
        for index in range(len(nums)):
            if nums[index] == target:
                return index
            elif nums[index] > target:
                return index
        return len((nums))
Enter fullscreen mode Exit fullscreen mode

My thought:
I use range(len(nums)) to iterate all numbers in nums. Check if there is the same number. Meanwhile, I will check if nums[index] > target. If this is True, which means the nums does not have the same number as target. So it will return the index, which is the exact position for insertion. Otherwise, return the length of the nums.

Feel free to leave questions!!!
Please let me know where can find good solutions for Python (Leetcode)

💖 💪 🙅 🚩
daniel20030312
猪猪

Posted on September 29, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Search-35. Search Insert Position
beginners Search-35. Search Insert Position

September 29, 2024