| 35 | Search Insert Position | 40.00% | 查找目标数字在数组中的排序,输出排序位置,先加再排序再查找 |
| 注意list是可变变量,用list.append()合并和list.sort()排序时,list自身已经改变了 用[]构造list:[x for x in nums if x<target]:返回x中小于target的所有元素, 形如 [0,1,2] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 23 13:55:51 2018
@author: vicky
"""
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return(nums.index(target))
else:
nums.append(target) #合并,list是可变变量,nums自身改变了
nums.sort() #排序
return nums.index(target)
if __name__ == "__main__":
nums=[1,3,5,6]
target=4
print(Solution().searchInsert(nums, target))
x=nums
class Solution(object):
def searchInsert(self, nums, target):
return len([x for x in nums if x<target])
#返回nums中小于target的元素个数,[x for x in nums if x<target]返回元素值
本文介绍了一种在有序数组中查找目标数字并确定其插入位置的方法。通过Python实现,利用列表的append()方法进行合并,sort()方法进行排序,并通过index()方法找到目标的位置。此外,还提供了一个更简洁的解决方案,直接计算小于目标值的元素数量。
106

被折叠的 条评论
为什么被折叠?



