Leetcode
  • Leetcode
  • 1. Two Sum
  • 7. Reverse Integer
  • 9. Palindrome Number
  • 13. Roman to Integer
  • 20. Valid Parentheses
  • 21. Merge Two Sorted Lists
  • 26. Remove Duplicates from Sorted Array
  • 27. Remove Element
  • 28. Implement strStr()
  • 35. Search Insert Position
  • 53. Maximum Subarray
  • 58. Length of Last Word
  • 66. Plus One
  • 876. Middle of the Linked List
  • 67. Add Binary
  • 69. Sqrt(x)
  • 83. Remove Duplicates from Sorted List
  • 14. Longest Common Prefix
  • 70. Climbing Stairs
  • 100. Same Tree
  • 101. Symmetric Tree
  • 104. Maximum Depth of Binary Tree
  • Untitled
Powered by GitBook
On this page

35. Search Insert Position

Previous28. Implement strStr()Next53. Maximum Subarray

Last updated 6 years ago

Given a sorted array 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 may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

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

Example 4:

Input: [1,3,5,6], 0
Output: 0

Solution:

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        i = 0
        while i < len(nums):
            if nums[i] >= target:
                break
            i += 1
        return i
https://leetcode.com/problems/search-insert-position/description/