目录
1 两数之和 Two Sum
7 整数反转 Reverse Integer
9 回文数 Palindrome Number
13 罗马数字转整数 Roman to Integer
14 最长公共前缀 Longest Common Prefix
20 有效的括号 Valid Parentheses
21 合并两个有序链表 Merge Two Sorted Lists
26 删除排序数组中的重复选项 Remove Duplicates from Sorted Array
27 移除元素 Remove Element
28 实现strStr() Implement strStr()
def twoSum1(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i in range(len(nums)):
if target - nums[i] in d:
return [d[target - nums[i]], i]
d[nums[i]] = i
def twoSum2(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i, num in enumerate(nums):
if target - num in d:
return [d[target - num], i]
d[num] = i
def reverse1(x):
"""
:type x: int
:rtype: int
"""
# -214783648 ~ 214783647
num = 0
a = abs(x)
while(a != 0):
temp = a % 10
num = num * 10 + temp
a = int(a/10) # 使用a//10结果不对
if x > 0 and num < 0x7fffffff:
return num
elif x < 0 and num <= 0x7fffffff:
return -num
else:
return 0
def reverse2(x):
"""
:type x: int
:rtype: int
"""
sign = x < 0 and -1 or 1
x = abs(x)
ans = 0
while(x):
ans = ans * 10 + x % 10
x = int(x/10)
return sign * ans if ans < 0x7fffffff else 0
def isPalindrome1(x):
if x < 0:
return False
else:
s = str(x)
return s == s[::-1]
def isPalindrome2(x):
z = x
y = 0
while x > 0:
y = y * 10 + x % 10
x = int(x/10)
return z == y
def romanToInt1(s):
# 思路:把字符串中符合特殊情况的挑出来
a = {"IV": 4, "IX": 9, "XL": 40, "XC": 90, "CD": 400, "CM": 900}
d = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
n = 0
e = []
for i in range(len(s) - 1):
c = s[i] + s[i+1]
if c in a.keys():
n += a[c]
e.append(i)
e.append(i+1)
for i in range(len(s)):
if i not in e:
n += d[s[i]]
return n
def romanToInt2(s):
# 思路:找到规律,如果字符串后一个比前一个大则减前一个的值
d = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
ans = 0
for i in range(len(s) - 1):
c = s[i]
cafter = s[i + 1]
if d[c] < d[cafter]:
ans -= d[c]
else:
ans += d[c]
ans += d[s[-1]]
return ans
def romanToInt3(s):
# 思路: 都加,如果后面大于前面则减去两个前面
d = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
result = 0
for i in range(len(s)):
if i > 0 and d[s[i]] > d[s[i-1]]:
result += d[s[i]] - 2 * d[s[i-1]]
else:
result += d[s[i]]
return result
def longestCommonPrefix1(strs):
result = ''
if len(strs) == 0:
return result
a, minstr = 0, min(strs, key=len)
for ch in minstr:
for i in range(1, len(strs)):
if strs[i][a] != ch:
return result
a, result = a + 1, result + ch
return result
def longestCommonPrefix2(strs):
if len(strs) == 0:
return ""
i = 0
j = 0
end = 0
while j < len(strs) and i < len(strs[j]):
if j == 0:
char = strs[j][i]
else:
if strs[j][i] != char:
break
if j == len(strs) - 1:
i += 1
j = 0
end += 1
else:
j += 1
return strs[j][:end]
def longestCommonPrefix3(strs):
"""
通过zip将每个字符串的字母按顺序放入一个元组中:
zip("abc", "abd")
[(a, b), (a, b), (c, d)]
再把元组变为集合即可消去重复元素,所以当集合长度为1时,说明所有字符串在这个位置的字母相等
"""
res = ""
if not strs:
return ""
for each in zip(*strs):
if len(set(each)) == 1:
res += each[0]
else:
return res
return res
def longestCommonPrefix4(strs):
if not strs:
return ""
for i in range(len(strs[0])):
for string in strs[1:]:
if i >= len(string) or string[i] != strs[0][i]:
return strs[0][:i]
return strs[0]
def isValid1(s):
"""
循环搜索()[]{}并删掉,最后剩余空字符串则为True
"""
k = ["[]", "{}", "()"]
while(s != ""):
n = 0
for i in range(3):
a = s.find(k[i])
if a >= 0:
s = s[:a] + s[a+2:]
print(s)
else:
n += 1
if n == 3:
return False
return True
def isValid2(s):
"""
从头开始检索如果遇到()[]{}就先加上再减去,如果最后为空列表则为True
"""
stack = []
d = ["()", "[]", "{}"]
for i in range(len(s)):
stack.append(s[i])
if len(stack) >= 2 and stack[-2]+stack[-1] in d:
stack.pop()
stack.pop()
return len(stack) == 0
def isValid3(s):
stack = []
lookup = {"(": ")", "{": "}", "[": "]"}
for parenthese in s:
if parenthese in lookup:
stack.append(parenthese)
elif len(stack) == 0 or lookup[stack.pop()] != parenthese:
return False
return len(stack) == 0
def mergeTwoLists(l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = dummy = ListNode(-1)
while l1 and l2:
if l1.val < l2.val:
head.next = l1
l1 = l1.next
else:
head.next = l2
l2 = l2.next
head = head.next
head.next = l1 or l2
return dummy.next
def initLink(data): # 创建新链表
a = ListNode(data[0])
p = a
# 逐个为 data 内的数据创建结点, 建立链表
for i in data[1:]:
node = ListNode(i)
p.next = node
p = p.next
p.next = None
return a
def prtLink(link): # 打印链表
a = []
while link is not None:
a.append(link.val)
link = link.next
print(a)
l1 = initLink([1, 2, 3])
prtLink(l1)
l2 = initLink([1, 3, 4])
prtLink(l2)
l3 = mergeTwoLists(l1, l2)
prtLink(l3)
def removeDuplicates1(nums):
s = set(nums)
nums[:] = []
for i in range(len(s)):
nums.append(sorted(list(s))[i])
return len(nums)
def removeDuplicates2(nums):
if len(nums) <= 1:
return len(nums)
slow = 0
for i in range(1, len(nums)):
if nums[i] != nums[slow]:
slow += 1
nums[slow] = nums[i]
return slow + 1
def removeDuplicates3(nums):
n = 1
if len(nums) > 0:
for num in range(1, len(nums)):
if nums[num] != nums[num-1]:
nums[n] = nums[num]
n += 1
else:
n = 0
return n
def removeElement1(nums, val):
while(1):
try:
nums.remove(val)
except ValueError:
break
return len(nums)
def removeElement2(nums, val):
i = 0
while i < len(nums):
if nums[i] == val:
del nums[i]
else:
i += 1
return len(nums)
def strStr1(haystack, needle):
return haystack.find(needle)
def strStr2(haystack, needle):
try:
n = haystack.index(needle)
except ValueError:
n = -1
return n
def strStr3(haystack, needle):
for i in range(0, len(haystack) - len(needle) + 1):
if haystack[i:i+len(needle)] == needle:
return i
return -1