首页 > 编程语言 > 详细

每日LeetCode - 35. 搜索插入位置(C语言和Python 3)

时间:2021-05-13 01:11:15      阅读:20      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

C语言

// 二分法
int searchInsert(int* nums, int numsSize, int target){
    int left = 0, right = numsSize - 1, ans = numsSize;
    while (left <= right) {
        int mid = ((right - left) >> 1) + left;
        if (target <= nums[mid]) {
            ans = mid;
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return ans;
}

Python 3

#暴力法
class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        i=0
        while i < len(nums):
            if target <= nums[i]:
                return i
            i+=1
        return i
#直接用python语法……          
class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        nums.append(target)
        nums.sort()
        return nums.index(target)

每日LeetCode - 35. 搜索插入位置(C语言和Python 3)

原文:https://www.cnblogs.com/vicky2021/p/14762203.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!