code 1
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
code:
nums=[2,7,5,8]target=12buff_dict={}for i in range(len(nums)): print(i) if nums[i] in buff_dict : print([buff_dict[nums[i]],i]) else: buff_dict[target-nums[i]]=i print(buff_dict)
output:
0{10: 0}1{10: 0, 5: 1}2[1, 2]3{10: 0, 5: 1, 4: 3}
笔记:
将和的另一个值,依次作为字典的键值存入字典中,遍历数组,确定差值是否在字典中,如果不在作为键存入,键值对应的值和数组的索引相同。如果差值在字典中,则输对应的字典中键对应的值。
code 2
找出字符串中第一个字符串中的字母的下标
s="leetcode"
return 0
s="loveleetcode"
return 2
code:
def firstUniqChar(self,s):
letter='abcdefghijklmnopqrstuvwxyz'
index=[s.index(l) for l in letters if s.count(l)==1]
return min(index) if len(index)>0 else -1
笔记:s.count()作用 方法用于统计字符串里某个字符出现的次数。s.index()一般用处是在序列中检索参数并返回第一次出现的索引,没找到就会报
code 3
给出一位整数,输出它顺序相反的数
例:输入123 输出321
数入-123 输出 -321
输入 120 输出 21
code :解法1
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
n=abs(x)
y=0
while n!=0:
y=10*y+n%10
n=n//10
if x<0:
y=-y
if y<(-2**31) or y>(2**31-1):
return 0
else:
return y
笔记:1对于整数,不需要像字符串,数组那样用len来确定长度,n!=0 就是一个不错判断。
2 “/”和“//”区别,前面是浮点数除法。后面是整数除法,**平方
解法 2:
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
s = list(str(x))
if x>=0:
res = s[::-1]
num = int(''.join(res))
else:
res = s[1:][::-1]
num = int(''.join(res))*(-1)
if num>(2**31)-1 or num<-(2**31): return 0
else:return num
笔记:1 把数字转化为字符串 2 b = a[i:j:s]这种格式呢,i,j与上面的一样,但s表示步进,缺省为1,i,表示a的起始索引,j表示要索引的结尾,s表示步长。s=-1时表示倒序
s='hello world\n'
print s[:-1]
打印 hello world