Home >Backend Development >Python Tutorial >Search- Search Insert Position

Search- Search Insert Position

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-09-29 12:10:03984browse

Search- 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))

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)

The above is the detailed content of Search- Search Insert Position. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn