Leetcode题解....ing python
Posted Cop & Bridegroom
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode题解....ing python相关的知识,希望对你有一定的参考价值。
文章目录
1. 两数之和[medium]
解题思路
保持每个对应位数的进制carry,对应位置进行运算就行,循环终止条件是l1 or l2 or carry;
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
temp = p = ListNode(None)
carry = 0
sum = 0
while l1 or l2 or carry:
sum = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry
p.next = ListNode(sum % 10)
p = p.next
carry = sum // 10
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return temp.next
7. 整数反转[easy]
解题思路
整数翻转转化为字符串翻转,之后再将其转为int类型,判断原始数值和翻转后的数组是否再给定的范围内即可
代码
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x > 2**31 - 1 or x < -2**31:
return 0
if x < 0 and x >= -2**31:
x = abs(x)
x = str(x)
s = x[::-1]
s = -int(s)
if s < -2**31:
return 0
return s
elif x >= 0 and x <= 2**31 - 1:
x = str(x)
s = x[::-1]
s = int(s)
if s > 2**31 - 1:
return 0
else:
return s
8. 字符串转换整数 (atoi)[M]
解题思路
此处撰写解题思路
代码
class Solution(object):
def myAtoi(self, s):
"""
:type s: str
:rtype: int
"""
result = int(*re.findall('^[\\+\\-]?\\d+', s.lstrip()))
if result < -2**31:
result = -2**31
elif result > 2**31 - 1:
result = 2**31 - 1
return result
#return max(min(int(*re.findall('^[\\+\\-]?\\d+', s.lstrip())), 2**31 - 1), -2**31)
9.回文数
解题思路
将整数变为字符串,如果整数为负数,直接判断不是回文,非负数则将字符串反转,比较反转后的int值和原值是否相等;
代码
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
# 将整数变为字符串
if x >=0:
s = str(x)
# 将字符串反转
s = s[::-1]
if int(s) == int(x):
return True
else:
return False
else:
return False
12. 整数转罗马数字
解题思路
定义一个列表数组,遍历数组,退出条件是nums = 0
将list 转为str()
- result.toString()
- result = ‘’.join(result)
代码
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
result = []
# 定义一个字典
# dict = {'I':1, 'IV':4, 'V':5, 'IX':10, 'X':10, 'XL':40, 'L':50, 'XC':90, 'C':100, 'CD':400, 'D':500, 'CM':900, 'M':1000}
dict = [
[1000, 'M'],
[900, 'CM'],
[500, 'D'],
[400, 'CD'],
[100, 'C'],
[90, 'XC'],
[50, 'L'],
[40, 'XL'],
[10, 'X'],
[9, 'IX'],
[5, 'V'],
[4, 'IV'],
[1, 'I'],
]
for value, key in dict:
while(num >= value):
result.append(key)
num -= value
if num == 0:
break
result = ''.join(result)
return result
15. 三数之和
解题思路
双指针+for循环
对 i for 循环,定义j,k 指针,遍历,找到符合条件的列表
对于不符合条件有几种
- nums 长度小于3 并且最小值>0
- nums[j] == nums[j+1] or nums[k] == nums[k-1]
- nums[i] + nums[j] + nums[k] > 0 or nums[i] + nums[j] + nums[k] < 0
代码
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
nums.sort()
for i in range(len(nums)):
j = i + 1
k = len(nums) - 1
if nums[i]>0 or len(nums)<3:
return result
if i > 0 and nums[i] == nums[i-1]:
continue
while(j < k):
if nums[i] + nums[j] + nums[k] == 0:
result.append([nums[i],nums[j],nums[k]])
while(j < k and nums[j] == nums[j+1]):
j = j + 1
while(j < k and nums[k] == nums[k-1]):
k = k - 1
j += 1
k -= 1
elif nums[i] + nums[j] + nums[k] < 0:
j += 1
elif nums[i] + nums[j] + nums[k] > 0:
k -= 1
return result
20. 有效的括号[easy]
解题思路
判断如果长度为奇数,直接返回false;
直接将配对括号去掉
代码
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
# 用栈求解
if len(s)%2 != 0:
return False
while '()' in s or '[]' in s or '{}' in s:
s = s.replace('[]','').replace('()','').replace('{}','')
return True if s == '' else False
21. 合并两个有序链表
解题思路
两个指针,一个头指针,一个移动指针,变换的都是移动指针,最后返回头指针的next;
cur.next = l1 if l1 is not None else l2
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
cur = ListNode()
temp = cur # 保存头指针,移动的是cur指针
while l1 and l2:
if l1.val <= l2.val:
cur.next = l1
l1 = l1.next
elif l1.val > l2.val:
cur.next = l2
l2 = l2.next
cur = cur.next
if l1 is not None:
cur.next = l1
elif l2 is not None:
cur.next = l2
return temp.next
27. 移除元素[Easy]
解题思路
计算除去val之后元素的个数,之后对nums进行排序
代码
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
count = nums.count(val)
l = len(nums) - count
j = 0
for i in range(len(nums)):
if nums[i] != val:
nums[j] = nums[i]
j += 1
return l
23. 合并K个升序链表
思路
- 将list每个list提取出来合并排序,
- 重新将list直接串成链表
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
result = []
for i in lists:
while i:
result.append(i.val)
i = i.next
first = cur = ListNode(-1)
result.sort()
for j in result:
cur.next = ListNode(j)
cur = cur.next
return first.next
26. 删除有序数组中的重复项[easy]
题目
给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
解题思路
如果后一个元素与前一个元素不相等的话,按顺序将元素zai nums数组中进行组合
代码
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
j = 1
for i in range(1,len(nums)):
if nums[i] != nums[i-1]:
nums[j] = nums[i]
j+=1
return j
53. 最大子序和
解题思路
- nums 长度为1 直接返回
- 先将max置为最小值,如果每一次加上下一个数sum值能变大,变换max值
代码
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
ans = []
max = -10e5
if len(nums) == 1:
return nums[0]
sum = 0
for i in range(len(nums)):
sum = sum + nums[i]
if sum >= max:
max = sum
if sum <=0:
sum = 0
return max
58. 最后一个单词的长度
解题思路
代码
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s = s.strip(" ")
l = s.replace(",", " ")
ans = l.split(" ")
result = ans[-1]
count = 0
count = len(result)
return count
67. 二进制求和
解题思路
- 将二进制转为十进制进行运算
- 将结果转为二进制(bin())
- 去除表示进制的前两个字符
代码
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
# 求解二进制,转为十进制,再转为二进制
t1 = int(a, 2)
t2 = int(b, 2)
sum = t1 + t2
ans = bin(sum)
return ans[2:] # 去除进制前缀
以上是关于Leetcode题解....ing python的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode]题解(python):112 Path Sum
[LeetCode]题解(python):133-Clone Graph
LeetCode | 0106. Construct Binary Tree from Inorder and Postorder Traversal从中序与后序遍历序列构造二叉树Python(示(代
[LeetCode]题解(python):101-Symmetric Tree