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]返回元素值