1榆鼠、兩數(shù)之和
給定一個(gè)整數(shù)數(shù)組 nums 和一個(gè)目標(biāo)值 target遥昧,請(qǐng)你在該數(shù)組中找出和為目標(biāo)值的那 兩個(gè) 整數(shù),并返回他們的數(shù)組下標(biāo)褥琐。你可以假設(shè)每種輸入只會(huì)對(duì)應(yīng)一個(gè)答案锌俱。但是,你不能重復(fù)利用這個(gè)數(shù)組中同樣的元素敌呈。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因?yàn)?nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
答案:
class Solution:
? ? def twoSum(self, nums, target):
? ? ? ? """
? ? ? ? :type nums: List[int]
? ? ? ? :type target: int
? ? ? ? :rtype: List[int]
? ? ? ? """
? ? ? ? hashmap = {}
? ? ? ? for index, num in enumerate(nums):
? ? ? ? ? ? another_num = target - num
? ? ? ? ? ? if another_num in hashmap:
? ? ? ? ? ? ? ? return [hashmap[another_num], index]
? ? ? ? ? ? hashmap[num] = index
? ? ? ? return None
注:enumerate() 函數(shù)
用于將一個(gè)可遍歷的數(shù)據(jù)對(duì)象(如列表贸宏、元組或字符串)組合為一個(gè)索引序列,同時(shí)列出數(shù)據(jù)和數(shù)據(jù)下標(biāo)磕洪,一般用在 for 循環(huán)當(dāng)中吭练。
enumerate(sequence, [start=0])
sequence -- 一個(gè)序列、迭代器或其他支持迭代對(duì)象析显。
start -- 下標(biāo)起始位置鲫咽。
返回 enumerate(枚舉) 對(duì)象。
2、整數(shù)反轉(zhuǎn)
給出一個(gè) 32 位的有符號(hào)整數(shù)分尸,你需要將這個(gè)整數(shù)中每位上的數(shù)字進(jìn)行反轉(zhuǎn)锦聊。假設(shè)我們的環(huán)境只能存儲(chǔ)得下 32 位的有符號(hào)整數(shù),則其數(shù)值范圍為 [?231,? 231 ? 1]寓落。請(qǐng)根據(jù)這個(gè)假設(shè)括丁,如果反轉(zhuǎn)后整數(shù)溢出那么就返回 0。
答案:
class Solution:
? ? def reverse(self, x):
? ? ? ? """
? ? ? ? :type x: int
? ? ? ? :rtype: int
? ? ? ? """
? ? ? ? if x==0:
? ? ? ? ? ? return 0
? ? ? ? str_x = str(x)
? ? ? ? x = ''
? ? ? ? if str_x[0] == '-':
? ? ? ? ? ? x += '-'
? ? ? ? x += str_x[len(str_x)-1::-1].lstrip("0").rstrip("-")
? ? ? ? x = int(x)
? ? ? ? if -2**31<x<2**31-1:
? ? ? ? ? ? return x
? ? ? ? return 0
3伶选、回文數(shù)
判斷一個(gè)整數(shù)是否是回文數(shù)史飞。回文數(shù)是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數(shù)仰税。
答案:
class Solution:
? ? def isPalindrome(self, x):
? ? ? ? """
? ? ? ? :type x: int
? ? ? ? :rtype: bool
? ? ? ? """
? ? ? ? if x < 0:
? ? ? ? ? ? return False
? ? ? ? else:
? ? ? ? ? ? y = str(x)[::-1]
? ? ? ? ? ? if y == str(x):
? ? ? ? ? ? ? ? return True
? ? ? ? ? ? else:?
? ? ? ? ? ? ? ? return False
注:str[len(str) -1::-1].lstrip("0").rstrip("-")
str[len(str) -1::-1]:字符串[開(kāi)始點(diǎn)构资,結(jié)束點(diǎn),步長(zhǎng)]陨簇,步長(zhǎng)為負(fù)吐绵,從右到左
lstrip("0"):左邊刪0
rstrip("-"):右邊刪-
4、羅馬字符轉(zhuǎn)數(shù)字
羅馬數(shù)字包含以下七種字符: I河绽, V己单, X, L耙饰,C纹笼,D 和 M。
字符? ? ? ? ? 數(shù)值
I? ? ? ? ? ? ?1
V? ? ? ? ? ? ?5
X? ? ? ? ? ? ?10
L? ? ? ? ? ? ?50
C? ? ? ? ? ? ?100
D? ? ? ? ? ? ?500
M? ? ? ? ? ? ?1000
例如苟跪, 羅馬數(shù)字 2 寫(xiě)做 II 廷痘,即為兩個(gè)并列的 1。12 寫(xiě)做 XII 件已,即為 X + II 笋额。 27 寫(xiě)做? XXVII, 即為 XX + V + II 。
通常情況下篷扩,羅馬數(shù)字中小的數(shù)字在大的數(shù)字的右邊兄猩。但也存在特例,例如 4 不寫(xiě)做 IIII瞻惋,而是 IV厦滤。數(shù)字 1 在數(shù)字 5 的左邊,所表示的數(shù)等于大數(shù) 5 減小數(shù) 1 得到的數(shù)值 4 歼狼。同樣地掏导,數(shù)字 9 表示為 IX。這個(gè)特殊的規(guī)則只適用于以下六種情況:
I 可以放在 V (5) 和 X (10) 的左邊羽峰,來(lái)表示 4 和 9趟咆。
X 可以放在 L (50) 和 C (100) 的左邊添瓷,來(lái)表示 40 和 90。?
C 可以放在 D (500) 和 M (1000) 的左邊值纱,來(lái)表示 400 和 900鳞贷。
給定一個(gè)羅馬數(shù)字,將其轉(zhuǎn)換成整數(shù)虐唠。輸入確保在 1 到 3999 的范圍內(nèi)搀愧。
答案:
def romanToInt(self, s):
? ? ? ? """
? ? ? ? :type s: str
? ? ? ? :rtype: int
? ? ? ? """
? ? ? ? a = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}? ? ? ??
? ? ? ? ans=0? ? ? ??
? ? ? ? for i in range(len(s)):? ? ? ? ? ??
? ? ? ? ? ? if i<len(s)-1 and a[s[i]]<a[s[i+1]]:? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? ans-=a[s[i]]
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? ans+=a[s[i]]
? ? ? ? return ans? ??
5、最長(zhǎng)公共前綴
編寫(xiě)一個(gè)函數(shù)來(lái)查找字符串?dāng)?shù)組中的最長(zhǎng)公共前綴疆偿。
如果不存在公共前綴咱筛,返回空字符串 ""。
答案:
class Solution:
? ? def longestCommonPrefix(self, strs):
? ? ? ? """
? ? ? ? :type strs: List[str]
? ? ? ? :rtype: str
? ? ? ? """
? ? ? ? if "" in strs:
? ? ? ? ? ? return ""
? ? ? ? n = len(strs)
? ? ? ? if n > 1:
? ? ? ? ? ? pr = ""
? ? ? ? ? ? for index,i in enumerate(strs[0]):
? ? ? ? ? ? ? ? pr += i
? ? ? ? ? ? ? ? for j in range(1, n):
? ? ? ? ? ? ? ? ? ? if pr not in strs[j][:index+1]:
? ? ? ? ? ? ? ? ? ? ? ? break
? ? ? ? ? ? ? ? else:
? ? ? ? ? ? ? ? ? ? continue
? ? ? ? ? ? ? ? break
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? return pr
? ? ? ? ? ? return pr[:-1]
? ? ? ? else:
? ? ? ? ? ? return "" if not n else strs[0]
注:下面的值在解釋器中作為布爾表達(dá)式時(shí)杆故,會(huì)被看做假
False? ?None? ?0? ?""? ? ()? ?[]? ? {}
循環(huán)內(nèi)使用break語(yǔ)句時(shí)迅箩,也是可以加else的,僅在沒(méi)有調(diào)用break時(shí)執(zhí)行处铛。
這里的幾個(gè)break饲趋、continue看了2個(gè)小時(shí)沒(méi)看懂,不開(kāi)心撤蟆,明天問(wèn)匡神奕塑。
def longestCommonPrefix(self, strs):#mengmeng
? ? ? ? """
? ? ? ? :type strs: List[str]
? ? ? ? :rtype: str
? ? ? ? """
? ? ? ? if strs==[]:
? ? ? ? ? ? return ""
? ? ? ? out = ""
? ? ? ? flag = 0
? ? ? ? for num,i in enumerate(strs[0]):
? ? ? ? ? ? # print(num,i)
? ? ? ? ? ? for j in strs:
? ? ? ? ? ? ? ? if j[:num+1]!=out+i:
? ? ? ? ? ? ? ? ? ? flag=1
? ? ? ? ? ? ? ? ? ? break
? ? ? ? ? ? if flag == 1:
? ? ? ? ? ? ? ? break
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? out = out+i
? ? ? ? return out
昨天糾結(jié),浪費(fèi)了太多時(shí)間家肯,以后注意一題不要超過(guò)30min爵川,新手切忌鉆牛角尖,今天和同事交流一下息楔,都覺(jué)得上面的程序難懂,換一個(gè)就是了扒披,下次千萬(wàn)不要浪費(fèi)時(shí)間值依。
class Solution:#yongyong
? ? def longestCommonPrefix(self, strs):
? ? ? ? """
? ? ? ? :type strs: List[str]
? ? ? ? :rtype: str
? ? ? ? """
? ? ? ? if len(strs) == 1:
? ? ? ? ? ? return strs[0]
? ? ? ? elif len(strs) == 0:
? ? ? ? ? ? return ""
? ? ? ? else:
? ? ? ? ? ? res = ""
? ? ? ? ? ? if_break=False
? ? ? ? ? ? for index, letter in enumerate(strs[0]):
? ? ? ? ? ? ? ? res += letter
? ? ? ? ? ? ? ? # print(res)
? ? ? ? ? ? ? ? for i in range(1, len(strs)):
? ? ? ? ? ? ? ? ? ? # print(strs[i][:index + 1])
? ? ? ? ? ? ? ? ? ? if res != strs[i][:index + 1]:
? ? ? ? ? ? ? ? ? ? ? ? if_break=True
? ? ? ? ? ? ? ? ? ? ? ? break
? ? ? ? ? ? ? ? if if_break==True:
? ? ? ? ? ? ? ? ? ? break
? ? ? ? ? ? if if_break == True:
? ? ? ? ? ? ? ? return res[:-1]
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? return res
法三:
from multiprocessing.dummyimport Poolas ThreadPool#kaiyue
question = ['flower', 'flow', 'flight']
def get_index(x:str, i:int):
return x[:i]
for iin range(1, str(question[0]).__len__()):
pool = ThreadPool(question.__len__())
a =set(pool.map(lambda x: get_index(x=x, i=i), question))
b =set(pool.map(lambda x: get_index(x=x, i=i+1), question))
pool.close()
if b.__len__() !=1:
print(a)
break