# 编程小白用Python刷LeetCode学习笔记——前100题

## 编程小白用Python刷LeetCode学习笔记

1.两数之和

class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i, n in enumerate(nums):
m = target - n
if m in d:
return [d[m], i]
else:
d[n] = i


7.反转整数

class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
tmp=abs(x)
sum=0
while tmp>0:
sum=sum*10+tmp%10
tmp=tmp//10
if x<0:
sum=-sum
if sum<2**31 and sum>-2**31:
return sum
else:
return 0



9.回文数

class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
strs=list(str(x))
tmp=[]
for value in strs:
tmp.insert(0,value)
return strs==tmp


class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0:
return False
high=1
while x/high>=10:
high*=10
while x//high==x%10:
x=x%high//10
high=high/100
if high<1:
return True
return False



I 1
V 5
X 10
L 50
C 100
D 500
M 1000

13.罗马数字转整数

I 可以放在 V (5) 和 X (10) 的左边，来表示 4 和 9。
X 可以放在 L (50) 和 C (100) 的左边，来表示 40 和 90。
C 可以放在 D (500) 和 M (1000) 的左边，来表示 400 和 900。


class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
rom_map={'I':1,
'V':5,
'X':10,
'L':50,
'C':100,
'D':500,
'M':1000}
last_num=None
result=0
for char in s:
curent_num=rom_map[char]
if last_num is None or last_num>=curent_num:
result+=curent_num
elif last_num<curent_num:
result+=curent_num-2*last_num
last_num=curent_num
return result


class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
sum=0
convert={'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1}
for i in range(len(s)-1):
#if (s[i]=='I' or s[i]=='X' or s[i]=='C') and convert[s[i]]<convert[s[i+1]]:
if convert[s[i]]<convert[s[i+1]]:
sum=sum-convert[s[i]]
else:
sum=sum+convert[s[i]]
return sum+convert[s[-1]]



14.最长公共前缀

class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""

if not strs:
return ''
s1 = min(strs)
s2 = max(strs)
for i,c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1



20.有效的括号

左括号必须用相同类型的右括号闭合。



class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
top_element=''
stack=[]
mapping={')':'(',']':'[','}':'{'}
for char in s:
if char in mapping:
if stack:
top_element=stack.pop()
else:
'#'
if mapping[char]!=top_element:
return False
else:
stack.append(char)
return not stack



21.合并两个有序链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1==None:
return l2
if l2==None:
return l1
if l1.val<=l2.val:
ret=l1
ret.next = self.mergeTwoLists(l1.next, l2)
else:
ret=l2
ret.next = self.mergeTwoLists(l1, l2.next)
return ret



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

// nums 是以“引用”方式传递的。也就是说，不对实参做任何拷贝
int len = removeDuplicates(nums);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
for (int i = 0; i < len; i++) {
print(nums[i]);
}

class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
pos=0
this_num=None
for num in nums:
if num!=this_num:
nums[pos]=num
this_num=num
pos+=1
return pos



35.搜索插入位置

class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if nums[0]>target:
return 0
if nums[-1]<target:
return len(nums)
for i in range(len(nums)):
if nums[i]==target:
return i
elif nums[i]<target and nums[i+1]>target:
return i+1


class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def bs(numlsit, l, r):
while l <= r:
mid = int((l + r) / 2)
if numlsit[mid] == target:
return mid
elif numlsit[mid] < target:
return bs(numlsit, mid+1, r)
else:
return bs(numlsit, l, mid-1)
return l

return bs(nums, 0, len(nums)-1)


53.最大子序和

class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sums=0
maxsum=nums[0]
for value in nums:
sums=sums+value
if maxsum<sums:
maxsum=sums
if sums<0:
sums=0
return maxsum


class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length=len(nums)
for i in range(1,length):
#当前值的大小与前面的值之和比较，若当前值更大，则取当前值，舍弃前面的值之和
subMaxSum=max(nums[i]+nums[i-1],nums[i])
nums[i]=subMaxSum#将当前和最大的赋给nums[i]，新的nums存储的为和值
return max(nums)



58.最后一个单词长度

class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
str = ''
count = 0
for i in s[::-1]:
if str != '' and i==' ':
return count
if i != ' ':
count = count+ 1
str = str + i
return count



66.加一

class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
num=0
for value in digits:
num=num*10+value
num=num+1
new_list=[None]*len(str(num))
i=len(str(num))-1
while num>0:
new_list[i]=num%10
num=num//10
i-=1
return new_list


class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
carry = 1
for i in reversed(range(0, len(digits))):
digit = (digits[i] + carry) % 10
carry = 1 if digit < digits[i] else 0
digits[i] = digit
if carry == 1:
return [1] + digits
return digits


69.x的平方根

class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
y=1
lasty=2
while y-lasty>=1 or lasty-y>=1:
lasty=y
y=(lasty+x/lasty)/2
return int(y)



class Solution:
def mySqrt(self, x):
left=0;right=x
while left<right:
mid=int((left+right)/2)
if x<mid**2:
right=mid
else:
left=mid+1
if left>1:
return left-1
else:
return left


70.爬楼梯

1. 1 阶 + 1 阶
2. 2 阶
示例 2：

3. 1 阶 + 1 阶 + 1 阶
4. 1 阶 + 2 阶
5. 2 阶 + 1 阶
**注意：**此时相当于求斐波那契数列的第n个数

class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n<=2:
return n
a=[0]*(n+1)
a[1]=1
a[2]=2
for i in range(3,n+1):
a[i]=a[i-1]+a[i-2]
return a[n]


88.合并两个有序数组

nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3

class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
num=nums1[:m]+nums2
for i in range(m+n):
value=min(num)
nums1[i]=value
num.remove(value)


class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
while m>0 and n>0:
if nums1[m-1]>=nums2[n-1]:
nums1[m+n-1]=nums1[m-1]
m-=1
else:
nums1[m+n-1]=nums2[n-1]
n-=1
if n>0:
nums1[:n]=nums2[:n]