zoukankan      html  css  js  c++  java
  • 0035-leetcode算法实现之搜索插入顺序-search-insert-position-python&golang实现

    给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

    请必须使用时间复杂度为 O(log n) 的算法。

    示例 1:

    输入: nums = [1,3,5,6], target = 5
    输出: 2
    示例 2:

    输入: nums = [1,3,5,6], target = 2
    输出: 1
    示例 3:

    输入: nums = [1,3,5,6], target = 7
    输出: 4
    示例 4:

    输入: nums = [1,3,5,6], target = 0
    输出: 0
    示例 5:

    输入: nums = [1], target = 0
    输出: 0

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/search-insert-position

    python

    # 搜索插入顺序
    class Solution:
        def searchInsert(self, nums: [int], target: int) -> int:
            n = len(nums)
            left, right = 0, n-1
            while left <= right:
                mid = left + ((right-left) >> 1)
                if target < nums[mid]:
                    right = mid - 1
                elif target > nums[mid]:
                    left = mid + 1
                else:
                    return mid
            # 4种情况
            # 1.target在所有元素前 [0,-1]
            # 2.target等于某个元素 mid
            # 3.target介于某2个元素之间 [left, right] -> right+1
            # 4.target在所有元素后 同上
            return right + 1
    
        # 暴力法 时间O(n),空间O(1)
        def searchInsert1(self, nums, target):
            """
            遍历解决3种情况,1.比首个元素小的,2.等于某个元素, 3.介于某两个元素之间
            :param nums:
            :param target:
            :return:
            """
            n = len(nums)
    
            for i in range(n):
                if nums[i] >= target:
                    return i
            # 情况4,大于最后一个元素
            return n
    
    if __name__ == "__main__":
        nums = [2,3,6,7,8,14,16]
        target1 = 0
        target2 = 9
        target3 = 8
        target4 = 18
    
        test = Solution()
        print(test.searchInsert1(nums, target1))
        print(test.searchInsert1(nums, target2))
        print(test.searchInsert1(nums, target3))
        print(test.searchInsert1(nums, target4))
        print('*'*20)
        print(test.searchInsert(nums, target1))
        print(test.searchInsert(nums, target2))
        print(test.searchInsert(nums, target3))
        print(test.searchInsert(nums, target4))
    

    golang

    package main
    
    import "fmt"
    
    func main() {
    	nums := []int{2, 3, 6, 7, 8, 14, 16}
    	target1 := 0
    	res1 := searchInsert(nums, target1)
    	fmt.Println(res1)
    }
    
    func searchInsert(nums []int, target int) int {
    	var n int = len(nums)
    	left := 0
    	right := n - 1
    	for left <= right {
    		var mid int = left + (right-left)>>1
    		if target > nums[mid] {
    			left = mid + 1
    		} else if target < nums[mid] {
    			right = mid - 1
    		} else {
    			return mid
    		}
    	}
    
    	return right + 1
    }
    
    func searchInsert1(nums []int, target int) int {
    	var n int = len(nums)
    
    	for i, v := range nums {
    		if v >= target {
    			return i
    		}
    	}
    
    	return n
    }
    
  • 相关阅读:
    【转】浅谈 C++ 中的 new/delete 和 new[]/delete[]
    指针与const
    【面经】【转】C程序的内存布局
    【面经】二叉树层次遍历
    【面经】【转】C++类型转换
    【转】fastdb中的数据字典
    AtCoder AGC043D Merge Triplets (DP、组合计数)
    AtCoder AGC024F Simple Subsequence Problem (字符串、DP)
    Codeforces 1110G Tree-Tac-Toe (博弈论)
    Luogu P5244 [USACO2019Feb Platinum] Mowing Mischief (动态规划、决策单调性)
  • 原文地址:https://www.cnblogs.com/davis12/p/15405053.html
Copyright © 2011-2022 走看看