主要是考虑到easy题目没什么好分析的, 故统一总结在一篇文章里. 留作记录.
收录leetcode1-100题中easy难度的题目. 带星号的表示经典题型, 或者有衍生题.
文章目录
- 1. Two Sum (Easy)
- 7. Reverse Integer (Easy)
- 9. Palindrome Number (Easy)
- 13. Roman to Integer (Easy)
- 14. Longest Common Prefix (Easy)
- 20. Valid Parentheses (Easy)
- 21. Merge Two Sorted Lists** (Easy)
- 26. Remove Duplicates from Sorted Array (Easy)
- 27. Remove Element (Easy)
- 28. Implement strStr() (Easy)
- 35. Search Insert Position (Easy)
- 38. Count and Say (Easy)
- 53. Maximum Subarray ** (Easy)
- 58. Length of Last Word (Easy)
- 67. Add Binary (Easy)
- 69. Sqrt(x) (Easy)
- 70. Climbing Stairs **(Easy)
- 83. Remove Duplicates from Sorted List (Easy)
- 88. Merge Sorted Array (Easy)
- 100. 相同的树
1. Two Sum (Easy)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
sum = []
i = 0
while i < len(nums) :
try:
j = nums.index(target-nums[i])
except ValueError,e:
pass
else:
if i!=j:
sum.extend([i,j])
return sum
finally:
i +=1
7. Reverse Integer (Easy)
# integer has a range.Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1].
class Solution:
def reverse(self, x: int) -> int:
if x == 0:
return 0
if x > 0:
s = str(x)
s = int(s[::-1])
else:
s = str(x)[1:]
s = -int(s[::-1])
if s > 2**31 - 1 or s < -(2**31):
return 0
return s
9. Palindrome Number (Easy)
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
x = str(x)
if x == x[::-1]:
return True
else:
return False
13. Roman to Integer (Easy)
https://leetcode.com/problems/roman-to-integer/
题目描述
把罗马字母转换成整型数字.
"""
前面的罗马字符后面如果小于后面的罗马字符, 结果非但不能加上前面的罗马字, 还要减去它.
所以num -= 2*pre. 如果前面的罗马字符大于后面的, 则可以直接加上后面的.
"""
class Solution:
def romanToInt(self, s: str) -> int:
value_roman = {
"M":1000, "D":500, "C":100, "L":50, "X":10, "V":5, "I":1}
pre = 0
num = 0
for i in s:
num += value_roman[i]
if value_roman[i] > pre:
num -= 2 * pre
pre = value_roman[i]
return num
14. Longest Common Prefix (Easy)
https://leetcode.com/problems/longest-common-prefix/
题目描述
给定一个字符串数组, 输出最大共同前缀
Input: [“flower”,“flow”,“flight”]
Output: “fl”
"""
从头遍历所有字符串, 直到不一样的字符出现.
"""
class Solution:
def longestCommonPrefix