LeetCode Search Insert Position

Source: Internet
Author: User

LeetCode Search Insert Position
Search Insert Position for solving LeetCode Problems

Original question

In an ordered array, if the target number exists, its subscript is returned; otherwise, the Base Value of the inserted position is returned.

Note:

No repeated numbers in the array

Example:

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

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

Solutions

It is also a binary search question. If the current number is a target number or the current number is greater than the target number and the previous number is smaller than the target number, the current subscript is returned; if the current number is the last one and is smaller than the target number, the last digit of the current base is returned.

AC Source Code
class Solution(object):    def searchInsert(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: int        """        length = len(nums)        start = 0        end = length        while start < end:            mid = (start + end) // 2            if nums[mid] == target or (nums[mid] > target                 and (mid == 0 or nums[mid - 1] < target)):                return mid            if mid == length - 1 and nums[mid] < target:                return mid + 1            if nums[mid] < target:                start = mid + 1            else:                end = midif __name__ == "__main__":    assert Solution().searchInsert([1, 3, 5, 6], 5) == 2    assert Solution().searchInsert([1, 3, 5, 6], 2) == 1    assert Solution().searchInsert([1, 3, 5, 6], 7) == 4    assert Solution().searchInsert([1, 3, 5, 6], 0) == 0

Please check out my Github for relevant source code.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.