deftwoSum(nums, target): hashmap={} for i,num in enumerate(nums): if hashmap.get(target - num) isnotNone: return [i,hashmap.get(target - num)] hashmap[num] = i #这句不能放在if语句之前,解决list中有重复值或target-num=num的情况
classSolution: deflengthOfLongestSubstring(self, s: str) -> int: longth = 0 for i in range(len(s)): dirct = [] dirct.append(s[i]) ls = 1 for j in range(i + 1, len(s)): if s[j] in dirct: break else: dirct.append(s[j]) ls += 1 continue if ls > longth: longth = ls return longth
哈哈哈,还是很c的写法。。
O(n^2)
看看别人的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: deflengthOfLongestSubstring(self, s: str) -> int: # 哈希集合,记录每个字符是否出现过 occ = set() n = len(s) # 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动 rk, ans = -1, 0 for i in range(n): if i != 0: # 左指针向右移动一格,移除一个字符 occ.remove(s[i - 1]) while rk + 1 < n and s[rk + 1] notin occ: # 不断地移动右指针 occ.add(s[rk + 1]) rk += 1 # 第 i 到 rk 个字符是一个极长的无重复字符子串 ans = max(ans, rk - i + 1) return ans
classSolution: deffindMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: i = j = k = 0; numssum = [] while i < len(nums1) or j < len(nums2): if i >= len(nums1): for z in range(j,len(nums2)): numssum.append(nums2[z]) k+=1 break elif j>=len(nums2): for z in range(i,len(nums1)): numssum.append(nums1[z]) k+=1 break else: if nums1[i] <= nums2[j]: numssum.append(nums1[i]) i+=1 else: numssum.append(nums2[j]) j+=1 k+=1 #print(len(numssum)) if len(numssum)%2 == 0: return((numssum[len(numssum)//2-1]+numssum[len(numssum)//2])/2) else: return numssum[len(numssum)//2]
classSolution: deflongestPalindrome(self, s: str) -> str: n = len(s) dp = [[False] * n for _ in range(n)] ans = "" # 子串的长度 lens for lens in range(n): # 子串的起始位置 i,最长位置i+lens for i in range(n): j = i + lens if j >= len(s): break if lens == 0: dp[i][j] = True elif lens == 1: dp[i][j] = (s[i] == s[j]) else: dp[i][j] = (dp[i + 1][j - 1] and s[i] == s[j]) if dp[i][j] and lens + 1 > len(ans): ans = s[i:j + 1] return ans
输入: s = “LEETCODEISHIRING”, numRows = 4 输出: “LDREOEIIECIHNTSG” 解释:
L D R E O E I I E C I H N T S G
解答
直接确定每个字符在哪行,然后按行输出就可以呢…找规律
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: #确定每个元素在哪一行,再按行输出....... defconvert(self, s: str, numRows: int) -> str: if numRows == 2or numRows >= len(s) : return s out = ['']*numRows j,k = 0,1 for i in s: out[j] += i j += k if j==0or j == numRows -1: k = -k return"".join(out)
盛最多水的容器
题目描述
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
classSolution: defmaxArea(self, height: List[int]) -> int: left,right = 0,len(height)-1 max_area = 0 while left < right: area = height[left if height[left] <= height[right] else right] * (right - left) max_area = area if area >= max_area else max_area if height[left] <= height[right]: left += 1 else: right -= 1
return max_area
整数转罗马数字
题目描述
罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000
例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。
输入: 1994 输出: “MCMXCIV” 解释: M = 1000, CM = 900, XC = 90, IV = 4.
解答
比较简单。。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defintToRoman(self, num: int) -> str: a = [1000,900,500,400,100,90,50,40,10,9,5,4,1] r = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I'] lens = len(a) roma = '' for i in range(lens): sums = num // a[i] num = num % a[i] roma = roma+(r[i]*sums) return roma if __name__ == "__main__": a = Solution print(a.intToRoman(a,1994))
罗马数字转整数
题目描述
罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000
例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。
classSolution: defromanToInt(self, s: str) -> int: a = [1000,900,500,400,100,90,50,40,10,9,5,4,1] r = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I'] roma = [] i2r = {} sum = 0 for i in range(len(a)): i2r[r[i]] = a[i] for ss in s: roma.append(ss) for i in range(len(roma)-1): if i2r[roma[i]] >= i2r[roma[i+1]]: sum += i2r[roma[i]] else: sum -= i2r[roma[i]] sum += i2r[roma[-1]] return sum
if __name__ == "__main__": a = Solution print(a.romanToInt(a,"MCMXCIV"))
三数之和
题目描述
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]
解答
刚开始做的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: defthreeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() sums = [] for i in range(len(nums)): a = 0 - nums[i] for j in range(i+1,len(nums)): b = a - nums[j] try: k = nums.index(b,j+1,len(nums)) except ValueError: continue else: if k > i and k > j: c = [nums[i],nums[j],nums[k]] if c notin sums: sums.append(c) return sums
超时了,后来仿照答案写的双指针也超时了,竟然是因为 not in 查找的时候耗时太多了,看来python自带的函数也不能乱用
classSolution: defthreeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() sums = [] for i in range(len(nums)): if i > 0and nums[i] == nums[i - 1]: continue a = 0 - nums[i] k = len(nums) - 1 for j in range(i + 1,len(nums)): if j > i + 1and nums[j] == nums[j - 1]: continue while j < k and nums[j] + nums[k] > a : k -= 1 if j == k: break if nums[j] + nums[k] == a: c = [nums[i],nums[j],nums[k]] #if c not in sums: sums.append(c) return sums
if __name__ == "__main__": a = Solution nums = [3,0,-2,-1,1,2] nums.sort() print(nums) print(a.threeSum(a,nums))
defletterCombinations(self, digits: str) -> List[str]: sum = [''] number_letter = {'2':['a','b','c'], '3':['d','e','f'], '4':['g','h','i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']} for i in digits: sum = [a + b for a in sum for b in number_letter[i]] return sum
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defremoveNthFromEnd(self, head: ListNode, n: int) -> ListNode: top = l = ListNode(None) i = 0 j = i - n l1 = head while head: if j >= 0: l.next = ListNode(l1.val) #print(l1.val) l1 = l1.next l = l.next i += 1 j += 1 head = head.next l1 = l1.next while l1: l.next = ListNode(l1.val) l1 = l1.next l = l.next return top.next
看一下写的简单的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defremoveNthFromEnd(self, head: ListNode, n: int) -> ListNode: ifnot head: return head dummy = l = r =ListNode(10086) dummy.next = head for i in range(n): r = r.next while r.next isnotNone: r = r.next l = l.next l.next = l.next.next return dummy.next
classSolution: defisValid(self, s: str) -> bool: while'()'in s or'{}'in s or'[]'in s: s = s.replace('()', '') s = s.replace('[]', '') s = s.replace('{}', '') return s == ''
if __name__ == "__main__": a = Solution s = "{[]}" print(a.isValid(a, s))
classSolution: defgenerateParenthesis(self, n: int) -> List[str]: res = [] defdfs(s:str,left:int,right:int): if left > n : return if left < right: return if left == n and right == n: res.append(s) dfs(s+'(',left+1,right) dfs(s+')',left,right+1)
classSolution: defnextPermutation(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. 13542 13245 """ for i in range(len(nums)-1,0,-1): if nums[i] > nums[i-1]: nums[i:] = sorted(nums[i:]) for j in range(i,len(nums)): if nums[j] > nums[i-1]: nums[i-1],nums[j] = nums[j],nums[i-1] break return nums.sort()
if __name__ == "__main__": a = Solution nums = [1,2,3] a.nextPermutation(a,nums) print(nums)