Python、java、go实现"搜索插入位置"的几种方法

给定一个有序数组和一个目标值,如果数组中有目标值就返回对应索引,如果没有就返回按序插入目标值的下标

假设数组中不存在重复值

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

1:enumerate()方法遍历数组

def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        for index, num in enumerate(nums):     #将数组转换为枚举类型
            if target <= num:                 
                return index
        return len(nums)   

2:折半法,将数组分成两半进行查找比较

def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        start = 0     #指向折半搜索头
        end = len(nums)-1    #指向折半搜索尾
        while start <= end:    #判断条件
            mid = (start+end)//2    #折半中间
            if nums[mid]==target:   
                return mid
            elif nums[mid]>target:   #根据对比大小,重新赋值折半头或尾
                end = mid-1
            else:
                start = mid+1
        return start

上面是 python 实现,下面是 java 实现的版本

public int searchInsert(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (target <= nums[i]) {
                return i;
            }
        }
        return nums.length;
    }

以下是 go 实现版本

func searchInsert(nums []int, target int) int {
	for index , elem:= range nums {
		if target <= elem {
			return index
		}
	}
	return len(nums)
}

算法题来自:https://leetcode-cn.com/problems/search-insert-position/description/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值