zoukankan      html  css  js  c++  java
  • Leecode刷题之旅-C语言/python-35.搜索插入位置

    /*
     * @lc app=leetcode.cn id=35 lang=c
     *
     * [35] 搜索插入位置
     *
     * https://leetcode-cn.com/problems/search-insert-position/description/
     *
     * algorithms
     * Easy (42.89%)
     * Total Accepted:    31.6K
     * Total Submissions: 73.6K
     * Testcase Example:  '[1,3,5,6]
    5'
     *
     * 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
     * 
     * 你可以假设数组中无重复元素。
     * 
     * 示例 1:
     * 
     * 输入: [1,3,5,6], 5
     * 输出: 2
     * 
     * 
     * 示例 2:
     * 
     * 输入: [1,3,5,6], 2
     * 输出: 1
     * 
     * 
     * 示例 3:
     * 
     * 输入: [1,3,5,6], 7
     * 输出: 4
     * 
     * 
     * 示例 4:
     * 
     * 输入: [1,3,5,6], 0
     * 输出: 0
     * 
     * 
     */
    int searchInsert(int* nums, int numsSize, int target) {
        int i;
        for(i=0;i<numsSize;i++){
            if(nums[i]>=target){
                return i;
            }
        }
        return numsSize;
    }

    这里就在数组中循环,找到比target大或者等于的位置就好。如果找不到的话,那target肯定就是最大的,返回numsize就行。

    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

    python:

    #
    # @lc app=leetcode.cn id=35 lang=python3
    #
    # [35] 搜索插入位置
    #
    # https://leetcode-cn.com/problems/search-insert-position/description/
    #
    # algorithms
    # Easy (42.89%)
    # Total Accepted:    31.6K
    # Total Submissions: 73.6K
    # Testcase Example:  '[1,3,5,6]
    5'
    #
    # 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
    # 
    # 你可以假设数组中无重复元素。
    # 
    # 示例 1:
    # 
    # 输入: [1,3,5,6], 5
    # 输出: 2
    # 
    # 
    # 示例 2:
    # 
    # 输入: [1,3,5,6], 2
    # 输出: 1
    # 
    # 
    # 示例 3:
    # 
    # 输入: [1,3,5,6], 7
    # 输出: 4
    # 
    # 
    # 示例 4:
    # 
    # 输入: [1,3,5,6], 0
    # 输出: 0
    # 
    # 
    #
    class Solution:
        def searchInsert(self, nums: List[int], target: int) -> int:
            for i in range(len(nums)):
                if(nums[i]>=target):
                    return i
            return len(nums)
  • 相关阅读:
    python 写入txt的新方法
    python 对excel进行截图
    python 关于excel弹窗——请注意,您的文档的部分内容可能包含了文档检查器无法删除的个人信息解决方法
    python win32com 读取带密码的excel
    移动硬盘——显示盘符但打不开
    python datetime和time的一些疑惑解答 及 获取上年同期、上月等日期
    pyinstaller 打包exe程序读不到配置文件No such file
    Python之——爱心代码参与情人节
    《易学设计模式》-笔记
    "高级"数据库小结
  • 原文地址:https://www.cnblogs.com/lixiaoyao123/p/10493898.html
Copyright © 2011-2022 走看看