# LeetCode小白入门——简单题目八题合集，每题两解

## 1.两数之和

def twoSum(nums, target):
j = -1
for i in range(1,len(nums)):
new_nums = nums[:i]
if target-nums[i] in new_nums:
j = new_nums.index(target-nums[i])
break
if j>=0:
return [j,i]

def twoSum(nums, target):
dict_ = {}
for i in range(len(nums)):
if target-nums[i] in dict_:
return [dict_[target-nums[i]],i]
else:
dict_[nums[i]] = i
• 方法一用时548ms，内存消耗14.8MB
• 方法二用时68ms，内存消耗14.9MB

## 7.整数反转

def reverse(x):
str1 = str(abs(x))
str2 = str1[::-1]
if x>=0:
num = int(str2)
else:
str3 = '-'+str2
num = int(str3)
if num < (-2) ** 31 or num > 2 ** 31 - 1:
return 0
else:
return num

def reverse(x):
temp = abs(x)
i = len(str(temp))
num = 0
while i>0:
num = num * 10 + temp % 10
temp = temp // 10
i -= 1
if x<0:
num = -num
if num<(-2)**31 or num>2**31-1:
return 0
else:
return num
• 方法一用时52ms，内存消耗13.7MB
• 方法二用时52ms，内存消耗13.4MB

## 13. 罗马数字转整数

def romanToInt(self, s: str) -> int:
dict_ = {"I": 1, "IV":4,"V": 5,"IX":9, "X": 10, "XL":40,"L": 50,
"XC":90,"C": 100,"CD":400,"D": 500, "CM":900,"M": 1000}
sum = 0
i = 0
while i< len(s) - 1:
if dict_[s[i]] < dict_[s[i + 1]]:
sum += dict_[s[i:i + 2]]
i += 2
else:
sum += dict_[s[i]]
i += 1
if i >= len(s):
return sum
else:
return sum + dict_[s[-1]]

def romanToInt(self, s: str) -> int:
dict_ = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
sum = 0
for i in range(len(s)-1):
if dict_[s[i]]

14. 最长公共前缀

def longestCommonPrefix(strs):
if len(strs) == 0:
return ""
str0 = strs[0]
for i in strs:
if len(str0) > len(i):
str0 = str0[:len(i)]
for j in range(len(str0)):
if str0[j] != i[j]:
str0 = str0[:j]
break
return str0

def longestCommonPrefix(strs):
words = list(zip(*strs))
str_ = ''
for i in words:
word = list(set(i))
if len(word) == 1:
str_ += word[0]
else:
break
return str_

20.有效的括号

def isValid(s):
if len(s)%2 != 0:
return False
while '()' in s or '[]' in s or '{}'in s:
s = s.replace('()','').replace('[]','').replace('{}','')
return s==''

def isValid(s):
if s == '':
return True
dict = {')':'(',']':'[','}':'{'}
stack = [0]
for i in s:
if i in ['(','[','{']:
stack.append(i)
elif dict[i] == stack[-1]:
stack.pop()
else:
stack.append(i)
return stack == [0]

26. 删除排序数组中的重复项

def removeDuplicates(nums):
market1,market2 = 0, 1
while market2

def removeDuplicates(nums):
for i in range(len(nums)-1,0,-1):
if nums[i] == nums[i-1]:
nums.pop(i)
return len(nums)

def removeDuplicates(nums) int:
i = 0
for j in range(len(nums)):
if nums[j]!=nums[i]:
nums[i+1] = nums[j]
i += 1
return i+1

28. 实现 strStr()

def strStr(haystack,needle):
m,n = len(haystack),len(needle)
for i in range(0,m-n+1):
if needle == haystack[i:i+n]:
return i
return -1

def strStr(haystack,needle):
m,n = len(haystack),len(needle)
mar1,mar2=0,0
while mar10:
mar1 = mar1-mar2+1 #回到匹配的下一位
mar2 = 0
else:
mar1 += 1
return mar1-n if mar2==n else -1

35. 搜索插入位置

def searchInsert(nums,target):
mar = 0
while mar= target:
return mar
mar += 1
return len(nums)

def searchInsert(nums,target):
left = 0
right = len(nums) - 1
while (left <= right):
mid = (right + left) // 2
if nums[mid] < target:
left = mid + 1
elif nums[mid] > target:
right = mid - 1
else:
return mid
return left