leetcode 全解(python版)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 全解(python版)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本著blabla的精神,在這里(可能會)給出leetcode的全部習題答案 --持續更新中...
1.給定一個整數數組nums和一個目標值target,請你在該數組中找出和為目標值的那兩個整數,并返回他們的數組下標。
ps:這個好簡單,好容易理解aaa,,BUT是個反例,,執行用時超過限制...
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
l = len(nums)
for i in range(l):
for j in range(l):
if nums[i] + nums[j] == target and (not i == j):
return (i,j)
下面系正確且耗時非常OK的解法
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
lookup = {}
for i in range(n):
tmp = target - nums[i]
if tmp in lookup:
return [lookup[tmp], i]
lookup[nums[i]] = i
3.給定一個字符串,請你找出其中不含有重復字符的最長子串的長度。
ps1:明明直接len(l)就已經解決了的,非要把l打印出來看著,用什么left,right來計算最長子串長度,折騰了一天也沒計算明白,len(l)出來結果那一瞬間哭遼
ps2:內存消耗太大,等待修正中...
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
l = [] # 記錄遍歷過的字符
count = 0 # 記錄每一個無重復字符的字串的長度
max_num = 0 # 記錄所有子串最長長度
if len(s) == 0:
return 0
if len(s) == 1:
return 1
for c in s:
if c not in l:
l.append(c)
count = len(l)
else:
if l.index(c) == len(l): #如果是重復的字符為列表中最后一個,例如abcc
l = [].append(c)
l = l[l.index(c) + 1 :]
l.append(c)
if count >= max_num:
max_num = count
return max_num
總結
以上是生活随笔為你收集整理的leetcode 全解(python版)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Could not find a sui
- 下一篇: MySQL进程杀掉后是killed