python刷题用leet_leetcode刷题--python

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的 两个 整数。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

class Solution(object):

def twoSum(self, nums, target):

"""

:type nums: List[int]

:type target: int

:rtype: List[int]

"""

for m in range (len(nums)):

for n in range (m+1,len(nums)):

if nums[m]+nums[n]==target:

return [m,n]

def twoSum(nums, target):

"""

:type nums: List[int]

:type target: int

:rtype: List[int]

"""

d = {}

for i, item in enumerate(nums):

tmp = target - item

for key, value in d.items():

if value == tmp:

return [key, i]

d[i] = item

return None

1189684-20190820140816264-1325999726.png

classSolution:def isPalindrome(self, x: int) ->bool:if str(x)[::-1]==str(x):returnTrueelse:return False

1189684-20190820141043847-2101726813.png

1189684-20190820141122187-86977499.png

class Solution:

def romanToInt(self, s: str) -> int:

roman_dic={'I':1, 'IV':3, 'V':5, 'IX':8, 'X':10, 'XL':30, 'L':50, 'XC':80, 'C':100, 'CD':300, 'D':500, 'CM':800, 'M':1000}

roman_sum=0

return sum(roman_dic.get(s[max(i - 1, 0):i + 1], roman_dic[n]) for i, n in enumerate(s))

#

# for i,n in enumerate(s):

# roman_sum+=roman_dic.get(s[max(i - 1, 0):i + 1], roman_dic[n])

# return roman_sum

1189684-20190821145321887-1474094775.png

class Solution:

def longestCommonPrefix(self, strs: List[str]) -> str:

res=""

for tmp in zip(*strs):

tmp_set=set(tmp)

if len(tmp_set)==1:

res+=tmp[0]

else:

break

return res

1189684-20190826172548265-1474284954.png

class Solution:

def addStrings(self, num1: str, num2: str) -> str:

add=0

res=""

new_num1=num1[::-1]

new_num2=num2[::-1]

if len(new_num1)>len(new_num2):

new_num2+="0"*(len(new_num1)-len(new_num2))

else:

new_num1+="0"*(len(new_num2)-len(new_num1))

n=max(len(new_num1),len(new_num2))

for i in range(n):

tmp=int(new_num1[i])+int(new_num2[i])+add

res+= str(tmp%10)

add=int(tmp/10)

if add!=0:

res+=str(add)

# 这里的if处理:当两个数相加为10或者100时,当最后一个add=1时,把进位打出来

return res[::-1]

1189684-20190827183709876-626414956.png

思路:

我们可以对bits 数组从左到右扫描来判断最后一位是否为一比特字符。当扫描到第 i 位时,如果 bits[i]=1,那么说明这是一个两比特字符,将 i 的值增加 2。如果 bits[i]=0,那么说明这是一个一比特字符,将 i 的值增加 1。

如果 i 最终落在了 bits.length-1 的位置,那么说明最后一位一定是一比特字符。

class Solution:

def isOneBitCharacter(self, bits) -> bool:

i=0

if len(bits) == 1:

return True

while i<(len(bits)-1):

if bits[i]==0:

i+=1

elif bits[i]==1:

i+=2

if i==len(bits):

return False

else:

return True

1189684-20190905174638369-1137796721.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值