leetcode 全解(python版)
2024-10-08 04:22:05
本着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
最新文章
- SQL分页语句三方案
- Oracle中使用REGEXP_SUBSTR,regexp_replace函数
- 微信浏览器的HTTP_USER_AGENT
- 11月13日上午ajax返回数据类型为JSON数据的处理
- test2
- javaScript 1
- MySQL索引和优化查询
- HDU 2809 God of War(DP + 状态压缩)
- jQuery 简单归纳总结
- DM8168 GPIO驱动与測试程序
- 关于64位Windows7系统下INF的安装问题
- SQL 使用存储过程创建报表的一点体会
- How do I get the lowest value of all the non zero value pixels?
- maxscale读写分离
- 博弈论进阶之SG函数
- mysql查询某一个字段是否包含中文字符
- JetBrains 授权服务器(License Server URLS)
- Android UI系列-----CheckBox和RadioButton(1)
- 201621123008 《Java程序设计》第12周学习总结
- chrome inspect 远程调试H5