leetcode
1. Two Sum
- if there are chinese characters in comment, you have to add
#coding:utf-8
in front of the.py
file, or there would be a problem. - the
enumerate()
function to get the index and value in a array at the same time - for each element, record the value need and the corresponding index
Sample Input 1:
nums = [2, 7, 11, 15], target = 9
Sample Output 1:
[0, 1]
Code
#coding:utf-8
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
enumerate()函数的功能
"""
# record the number need and the position who need it
dic={}
for i,num in enumerate(nums):
if num in dic:
return [dic[num], i]
else:
dic[target-num]=i
s=Solution()
print(s.twoSum([2, 7, 11, 15],9))
2. Add Two Numbers
- robustness the input array is not
nullptr
and returnnullptr
if the twoptr
are allnullptr
, but it’s not requested in this problem - only when the
l1 or l2
is true, fill the nextListNode
Sample Input 1:
(2 -> 4 -> 3) + (5 -> 6 -> 4)
Sample Output 1:
7 -> 0 -> 8
Code
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 is None:
return l2
if l2 is None:
return l1
ans=ListNode(0)
tmp=ans
carry=0
while(l1 or l2):
temp=0
if l1:
temp+=l1.val
l1=l1.next
if l2:
temp += l2.val
l2=l2.next
temp+=carry
carry=temp//10
temp=temp%10
nxt=ListNode(0)
tmp.next=ListNode(temp)
tmp=tmp.next
if carry == 1:
tmp.next=ListNode(1)
del tmp
return ans.next
3. Longest Substring Without Repeating Characters
- there must be two-level nested loop, when the repeating element occurs, break inter-loop and add one in outer-loop
- only in this way, you can consider all the situations
Sample Input 1:
“abcabcbb”
Sample Output 1:
3
Sample Input 2:
“bbbbb”
Sample Output 2:
1
Sample Input 3:
“pwwkew”
Sample Output 3:
3
Code
#coding:utf-8
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
s1=set()
num=0
maxnum=0
for i in range(len(s)):
s1.clear()
num=0
for j in s[i:]:
if j not in s1:
num+=1
s1.add(j)
else:
break
if num>maxnum:
maxnum=num
return maxnum
s=Solution()
print(s.lengthOfLongestSubstring("abcabcbb"))
4. Median of Two Sorted Arrays
- if you want to type simple code, merge the two array and sort it, but the time complexity is large.
- here I exchange space complexity with time complexity.
Sample Input 1:
nums1 = [1, 3]
nums2 = [2]
Sample Output 1:
2
Sample Input 2:
nums1 = [1, 2]
nums2 = [3, 4]
Sample Output 2:
2.5
Code
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
len1,len2=len(nums1),len(nums2)
l=len1+len2
n=l//2
res=[]
flag=0
while nums1 and nums2 and flag <= n:
if nums1[0]<nums2[0]:
res.append(nums1.pop(0))
else:
res.append(nums2.pop(0))
flag+=1
while len(res)<n+1:
res.append(nums1.pop(0) if nums1 else nums2.pop(0))
return res[n] if l%2==1 else (res[n]+res[n-1])/2
s=Solution()
print(s.findMedianSortedArrays([1,2],[3,4]))
5. Longest Palindromic Substring
- the idea is loop each character in
s
and center-expend it until the border or not suitable —s[l]!=s[r]
Sample Input 1:
“babad”
Sample Output 1:
“bab”
Sample Input 2:
“cbbd”
Sample Output 2:
“bb”
Code
#coding:utf-8
# 中心拓展法求最大回文子串
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
start=end=0
for i in range(len(s)):
len1=self.expend(s,i,i)
len2=self.expend(s,i,i+1)
maxlen=max(len1,len2)
if maxlen>end-start+1:
start=i-(maxlen-1)//2
end=i+maxlen//2
return s[start:end+1]
def expend(self,s,l,r):
# for the last time, the l is subtract one and r add one, but the current l and r are not suitable,
# so you have to return the r-l-1.
while l>=0 and r<len(s) and s[l]==s[r]:
l-=1
r+=1
return r-l-1
s=Solution()
print(s.longestPalindrome("babad"))
6. Zigzag Conversion
- the main idea is insert each row array using
step
, so you have to check whether thenumRows
is one
Sample Input 1:
s = “PAYPALISHIRING”, numRows = 3
Sample Output 1:
“PAHNAPLSIIGYIR”
Sample Input 2:
s = “PAYPALISHIRING”, numRows = 4
Sample Output 2:
“PINALSIGYAHRPI”
Code
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
step=1
arr=['' for i in range(numRows)]
row=0
for c in s:
if row==0:
step=1
if row==numRows-1:
step=-1
arr[row]+=c
row+=step
return ''.join(arr)
7. Reverse Integer
- the input is
int
type, but you have to check whether the output is alsoint
Sample Input 1:
123
Sample Output 1:
321
Sample Input 2:
-123
Sample Output 2:
-321
Sample Input 3:
120
Sample Output 3:
21
Code
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
minus=False
if x<0:
minus=True
x=-x
ans=0
while x:
ans=ans*10+x%10
x//=10
if minus:
ans=-ans
if ans > 2147483647 or ans < -2147483648:
return 0
return ans
s=Solution()
print(s.reverse(1534236469))
8. String to Integer (atoi)
- first to check whether the str is null
- then to check the symbolic bit, if there is a symbolic bit, record it and to check whether the remaining is null
- if the remaining string is not null, to check whether the remaining is a number
- finally, check whether the ans is in range
int
Sample Input 1:
“42”
Sample Output 1:
42
Sample Input 2:
" -42"
Sample Output 2:
-42
Sample Input 3:
“4193 with words”
Sample Output 3:
4193
Sample Input 4:
“words and 987”
Sample Output 4:
0
Sample Input 5:
“-91283472332”
Sample Output 5:
-2147483648
Code
class Solution:
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
str=str.strip()
if str=='':
return 0
flag=''
i = 0
if str[0]=='+' or str[0]=='-':
flag='-' if str[0]=='-' else ''
i+=1
if str[1:]=='':
return 0
ans=0
if str[i] < '0' or str[i] > '9':
# print("取出第一個符號後爲空")
return 0
while i<len(str) and str[i]>='0' and str[i]<='9':
ans=ans*10+int(str[i])
i+=1
if flag=='-':
ans=-ans
if ans>2147483647:
return 2147483647
if ans<-2147483648:
return -2147483648
return ans
s=Solution()
print(s.myAtoi("1"))
9. Palindrome Number
- if the input is less than zero, return
False
directly
Sample Input 1:
121
Sample Output 1:
True
Sample Input 2:
-121
Sample Output 2:
False
Sample Input 3:
10
Sample Output 3:
True
Code
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0:
return False
origin=x
ans=0
while x:
ans=ans*10+x%10
x//=10
return ans==origin
s=Solution()
print(s.isPalindrome(10))
10. Regular Expression Matching
- here, the regular rule is a difficult problem
Sample Input 1:
s = “aa”
p = “a”
Sample Output 1:
false
Sample Input 2:
s = “aa”
p = “a*”
Sample Output 2:
true
Sample Input 3:
s = “ab”
p = “.*”
Sample Output 3:
true
Sample Input 4:
s = “aab”
p = “cab”
Sample Output 4:
true
Sample Input 5:
s = “mississippi”
p = “misisp*.”
Sample Output 5:
false
Code
class Solution:
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
dp = [[False for _ in range(len(p) + 1)] for _ in range(len(s) + 1)]
dp[0][0] = True
for j in range(2,len(p) + 1):# start from the second element to the last element
if p[j - 1] == '*':
dp[0][j] = dp[0][j - 2]
for i in range(1,len(s) + 1):
for j in range(1,len(p) + 1):
if p[j - 1] == '*':
dp[i][j] = dp[i][j-1] or dp[i][j-2] or (dp[i-1][j] and (s[i-1] == p[j-2] or p[j-2] == '.'))
elif p[j-1] == '.' or s[i-1] == p[j - 1]:
dp[i][j] = dp[i-1][j-1]
return dp[len(s)][len(p)]
s = Solution()
print(s.isMatch("", ".b*"))
53
enumerate(nums)
: extract the index and value from array- when the currentSum is less than or equals zero, it would be meaningless for the situation when maxSum is more than zero
- when the maxSum is less than zero, traverse all the situations
Sample Input 1:
[-2,1,-3,4,-1,2,1,-5,4]
Sample Output 1:
6
Code
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxSum=nums[0]
for idx, val in enumerate(nums):
tempNums=nums[idx:]
currentSum=0
for i in tempNums:
currentSum+=i
if maxSum>0 and currentSum<=0:
idx+=i
break
if currentSum>maxSum:
maxSum=currentSum
return maxSum
s=Solution()
print(s.maxSubArray([-2,-1]))
58
- last word means the last non-space word, so
s=s.strip()
to delete the space of beginning and end - when the current character is
' '
, recount the word
Sample Input 1:
“Hello World”
Sample Output 1:
5
Code
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s=s.strip()
cur_len=0
for i in s:
if i==" ":
cur_len=0
else:
cur_len+=1
return cur_len
s=Solution()
print(s.lengthOfLastWord("Hello World"))
66
len(l)
: return the length of listl.insert(0,5)
: insert 5 to the position of index 0 on the list, the position is represented by a number
Sample Input 1:
[1,2,3]
Sample Output 1:
[1,2,4]
Sample Input 2:
[4,3,2,1]
Sample Output 2:
[4,3,2,2]
Code
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
carry=0
len1=len(digits)
for i in range(len1):
temp=digits[len1-i-1]+carry
if i==0:
temp+=1
carry=temp//10
temp%=10
digits[len1 - i - 1]=temp
if carry==1:
# here the iterator is not necessary
digits.insert(0,1)
return digits
s=Solution()
print(s.plusOne([9,9]))
67
- reverse the list:
l[::-1]
Sample Input 1:
a = “11”, b = “1”
Sample Output 1:
“100”
Sample Input 2:
a = “1010”, b = “1011”
Sample Output 2:
“10101”
Code
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a=a[::-1]
b=b[::-1]
l1=len(a)
l2=len(b)
l=min(l1,l2)
s=''
if l1==l:
a+='0'*(l2-l)
else:
b+='0'*(l1-l)
l=len(a)
carry=0
for i in range(l):
temp=int(a[i])+int(b[i])+carry
carry=temp//2
temp%=2
s+=str(temp)
if carry==1:
s+='1'
return s[::-1]
s=Solution()
print(s.addBinary("1","111"))
69
- the time complexity must be
logn
, then
won’t be accepted
Sample Input 1:
4
Sample Output 1:
2
Sample Input 1:
8
Sample Output 1:
2
Code
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
start=1
end=x
mid=(start+end)//2
while end-start!=1:
if mid*mid==x:
return mid
if mid*mid<x:
start=mid
if mid*mid>x:
end=mid
mid=(start+end)//2
return mid
s=Solution()
print(s.mySqrt(4))