Leetcode Search Insert Position

    这道题算法很简单,遍历已经排好序的数组返到目标数字的位置,如果找不到目标数字,就返回此数字按序应该插入到数组中的位置。有一个要处理的细节就是如何将输入形如[1,2,3,4], 2的字符串转化为数组。在查找相关字符串处理方法之后,我选择用replace(old,new)来处理字符串,将字符串中的'[',']',',',' '转化为空字符串,这样字符串中就只剩下数组。将数组中最后一个数字pop,因为这是目标数字。随后遍历数组与这个数字相比较,记录数字的位置即可。代码如下所示:
arr=input()
arr=arr.replace('[','').replace(']','').replace(',','').replace(' ','')
num=[int(n) for n in arr]
a=num.pop()
l=len(num)
pos=0
temp=0
for i in range(0,l):
	if a==num[i]:
		print(pos)
		temp=1
		break
	elif a > num[i]:
		pos+=1	

if temp==0:
	print(pos)		
		


猜你喜欢

转载自blog.csdn.net/qq_40169140/article/details/80070759