腾讯精选练习50题(LeetCode)

两数相加(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
c1=[]
c2=[]
while l1:
c1.append(l1.val)
l1=l1.next
while l2:
c2.append(l2.val)
l2=l2.next
j1=-1
j2=-1
sum1=0
sum2=0
for i in range(len(c1)):
sum1=sum1*10+c1[j1]
j1=j1-1
for i in range(len(c2)):
sum2=sum2*10+c2[j2]
j2=j2-1
res=sum1+sum2
p=head=node=ListNode(None)
l=len(str(res))
while l:
node=ListNode(res%10)
p.next=node
p=node
res/=10
l-=1
return head.next

寻找两个正序数组的中位数(hard)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
for i in nums2:
nums1.append(i)
nums1 = sorted(nums1)
if len(nums1)%2 !=0:
return nums1[len(nums1)/2]
else:
return (nums1[len(nums1)/2]+nums1[len(nums1)/2-1])/2.0

最长回文子串(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
char* longestPalindrome(char* s) {
int i,j,k,t,n,l;
int count=0;
int a=0;
char* ret = (char*)malloc(1001);
memset(ret,0,1001);
//int m[1000];
//char *m=(char *)malloc(sizeof(char)*strlen(s));
t=strlen(s);
for(i=t;i>0;i--){
for(j=0;j<t-i+1;j++){
count=0;
n=j+i-1;
for(k=j;k<i/2+j;k++){
if(s[k]==s[n--]){
count++;
}
else
break;
}
if(count==i/2)
break;
else
continue;
}
if(count==i/2)
break;
else
continue;
}
for(l=j;l<j+i;l++){
ret[a++]=s[l];
}
return ret;
}

整数反转(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
int reverse(int x) {
int t,sum=0;
while(x!=0){
t=x%10;
x=x/10;
if(sum>2147483647/10||(sum==2147483647/10 && t>7))
return 0;
if(sum<-2147483648/10||(sum==-2147483648/10 && t<-8))
return 0;
sum=sum*10+t;
}
return sum;
}

字符串转换整数(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution(object):
def myAtoi(self, s):
"""
:type s: str
:rtype: int
"""
res=""
flag=1
temp1=["0","1","2","3","4","5","6","7","8","9"]
temp2=["-","+"]
temp=0
for i in range(len(s)):
if s[i]!=" ":
temp=i
break
s=s[temp:]
if len(s)==0 or (s[0] not in temp1 and s[0] not in temp2):
return 0
elif s[0] in temp1:
for i in range(len(s)):
if s[i] in temp1:
res += s[i]
else:
break
if int(res) - 2147483647 > 0:
return 2147483647
else:
return int(res)
elif s[0] in temp2:
for i in range(1,len(s)):
if s[i] in temp1:
flag=0
res += s[i]
else:
break
if flag:
return 0
elif s[0]=="-":
if -int(res) - (-2147483648) >= 0:
return -int(res)
else:
return -2147483648
elif s[0]=="+":
if int(res) - 2147483647 > 0:
return 2147483647
else:
return int(res)
else:
return 0

回文数(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
bool isPalindrome(int x) {
int k,t,sum=0;
if(x<0)
return false;
else
{
k=x;
while(x!=0){
t=x%10;
sum=sum*10+t;
x=x/10;
}
if(sum==k)
return true;
else
return false;
}
return 0;
}

盛最多水的容器(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i=0
j=len(height)-1
res=0
while i<j:
h=min(height[i],height[j])
res=max(res,h*(j-i))
if height[i]>height[j]:
j-=1
else:
i+=1
return res

最长公共前缀(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs)==0:
return ""
c=[]
for i in range(len(strs)):
c.append(len(strs[i]))
minl = min(c)
s=''
for i in range(minl):
res=[]
for j in range(len(strs)):
res.append(strs[j][i])
if res[1:] == res[:-1]:
s+=strs[j][i]
else:
break
return s

三数之和(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
#第一种方法,可行但超时
# if len(nums)==0 or len(nums)==1 or len(nums)==2:
# return []
# sum_two=[]
# d={}
# res=[]
# count=0
# for i in range(len(nums)-1):
# for j in range(i+1,len(nums)):
# d[count]=[i,j]
# sum_two.append(nums[i]+nums[j])
# count+=1
# # print(d)
# # print(sum_two)
# for i in range(len(nums)):
# for j in range(len(sum_two)):
# if i not in d[j] and nums[i]+sum_two[j]==0:
# temp = [nums[d[j][0]]] + [nums[i]] + [nums[d[j][1]]]
# temp.sort()
# if temp not in res:
# res.append(temp)
# # res = list(set([tuple(t) for t in res]))
# # res = list([list(l) for l in res])
# return res

d = {}
# n = len(nums)
res = []
for i in range(len(nums)):
d = {}
for j in range(i + 1, len(nums)):
key = nums[j]
if key in d:
value = d[key] + [key]
value.sort()
if value not in res:
res.append(value)
key = -nums[i] - nums[j]
if key not in d:
d[key] = [nums[i], nums[j]]
return res

最接近的三数之和(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
res=[]
nums.sort()
for i in range(len(nums)):
low=i+1
high=len(nums)-1
while low<high:
sums=nums[i]+nums[low]+nums[high]
res.append(sums)
if sums==target:
return target
elif sums<target:
low+=1
else:
high-=1
res.sort()

if target<=res[0]:
return res[0]
if target>=res[-1]:
return res[-1]
if target in res:
return target
for i in range(1,len(res)):
if target>res[i-1] and target<res[i]:
a=target-res[i-1]
b=res[i]-target
if a>b:
return res[i]
else:
return res[i-1]

有效的括号(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
c=[]
j=0
if s=='':
return True
if s[0]==')' or s[0]==']' or s[0]=='}':
return False
for i in range(len(s)):
if len(c)==0:
c.append(s[i])
else:
if (c[-1]=='(' and s[i]==')') or (c[-1]=='[' and s[i]==']') or (c[-1]=='{' and s[i]=='}'):
c.pop(-1)
else:
c.append(s[i])
if len(c)==0:
return True
else:
return False

合并两个有序链表(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res=ListNode(None) #合并之后的新数组
p=res #保持头节点不动
if l1==None:
res.next=l2
return res.next
if l2==None:
res.next=l1
return res.next
while l1 and l2:
if l1.val < l2.val:
p.next=l1
l1=l1.next
else:
p.next=l2
l2=l2.next
p=p.next
if l1: #如果l1还没循环结束
p.next=l1
else: #如果l2还没循环结束
p.next=l2
return res.next

合并K个升序链表(hard)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
#如果lists为空,直接返回空
if len(lists)==0:
return None
#temp用来存两个单链表合并后的结果
temp=ListNode()
temp.val=None #将初始temp值置空
#从第一个升序链表开始比较
for i in range(len(lists)):
#保存temp和每一个升序链表比较后的结果
node=ListNode()
#如果当前链表为空,直接将node指向temp,并开始比较下一个链表
if lists[i]==None:
node.next=temp
continue
#如果temp为空,node指向当前链表并将temp指向node
if temp==None:
node.next=lists[i]
temp=node.next
continue
#两个都不为空,需要一个保存node节点,所以使用head开始向后比较
head=node
while temp !=None and lists[i]!=None:
if temp.val>lists[i].val:
head.next=lists[i]
head=head.next
lists[i]=lists[i].next
else:
head.next=temp
head=head.next
temp=temp.next
if temp!=None:
head.next=temp
if lists[i]!=None:
head.next=lists[i]
#两个链表比较完毕后将temp重置,并开始下一轮的比较
temp=node.next
#最后返回node节点
return node.next.next

删除有序数组中的重复项(easy)

1
2
3
4
5
6
7
8
9
10
11
12
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
c=0
for i in range(1,len(nums)):
if nums[i]!=nums[c]:
nums[c+1]=nums[i]
c+=1
return c+1

搜索旋转排序数组(medium)

1
2
3
4
5
6
7
8
9
10
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
return -1

字符串相乘(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
# return str(int(num1)*int(num2))
res = 0
for i in range(1,len(num1)+1):
for j in range(1, len(num2)+1):
res += int(num1[-i]) * int(num2[-j]) *10**(i+j-2)
return str(res)

全排列(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
def trace(path,choice):
if len(path)==len(nums):
res.append(path[:])
for i in choice:
if i in path:
continue
path.append(i)
trace(path,choice)
path.pop()
trace([],nums)
return res

最大子序和(easy)

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==1:
return nums[0]
for i in range(1,len(nums)):
nums[i] = nums[i]+max(nums[i-1],0)
return max(nums)

螺旋矩阵(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
res=[]
while len(matrix)!=0:
for i in matrix[0]:
res.append(i)
matrix.pop(0)
matrix=list(zip(*matrix))
matrix.reverse()
return res

螺旋矩阵II(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n==1:
return [[1]]
res=[[n*n-1],[n*n]]
i=n*n-2
while i>=1:
for j in range(len(res)):
res[j].insert(0,i)
i-=1
res=list(map(list,zip(*res)))
for j in res:
j.reverse()
return res

旋转链表(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head==None:
return head
node=head
count=0
while node!=None:
count+=1
pre=node
node=node.next
s=k%count
t=count-s
pre.next=head
for i in range(t):
prenode=head
head=head.next
prenode.next=None
return head

不同路径(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
res=[[1]*n]*m
# print(res)
for i in range(1,m):
for j in range(1,n):
res[i][j]=res[i][j-1]+res[i-1][j]
return res[-1][-1]

爬楼梯(easy)

1
2
3
4
5
6
7
8
9
10
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
res=[1,2,3]
for i in range(n-3):
res.append(res[-1]+res[-2])
return res[n-1]

子集(medium)

1
2
3
4
5
6
7
8
9
10
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res=[[]]
for i in nums:
res+=[j+[i] for j in res]
return res

合并两个有序数组(easy)

1
2
3
4
5
6
7
8
9
10
11
12
void merge(int* nums1, int m, int* nums2, int n) {
int i = m - 1,j = n - 1,k = m + n - 1;
while(i >= 0 && j >= 0)
{
if(nums1[i] > nums2[j])
nums1[k--] = nums1[i--];
else
nums1[k--] = nums2[j--];
}
while(j >= 0)
nums1[k--] = nums2[j--];
}

格雷编码(medium)

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
#先右移再异或
res=[]
for i in range(2**n):
res.append(i^i>>1)
return res

二叉树的最大深度(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right))+1

买卖股票的最佳时机(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
# max_num=0
# if len(prices)==0:
# return 0
# for i in range(1,len(prices)):
# if prices[i]-min(prices[:i])>max_num:
# max_num = prices[i]-min(prices[:i])
# return max_num

max_num=0
if len(prices)==0:
return 0
min_num=prices[0]
for i in range(1,len(prices)):
min_num = min(min_num,prices[i-1])
if prices[i]-min_num>max_num:
max_num = prices[i]-min_num
return max_num

买卖股票的最佳时机II(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
sum=0
res=[]
temp=[]
#这段用来分割连续增加的点
for i in range(1,len(prices)):
if prices[i]<prices[i-1]:
temp.append(i)
if len(prices) not in temp:
temp.append(len(prices))
temp.insert(0,0)

#这段用来将每个连续增加段存入res
for i in range(1,len(temp)):
res.append(prices[temp[i-1]:temp[i]])
#计算每个段中最大值和最小值并累加
for i in res:
if len(i)>=2:
sum+=(max(i)-min(i))
return sum

二叉树的最大路径和(hard)

1
2


只出现一次的数字(easy)

1
2
3
4
5
6
7
8
9
10
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for num in nums:
a = a ^ num
return a

环形链表(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head==None or head.next==None:
return False
p=head
q=head.next
while p:
if q.next==p:
return True
else:
if q.next==None:
return False
if q.next.next==None:
return False
p=p.next
q=q.next.next
return False

环形链表II(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
res=[]
node=head
while node!=None:
if node.next not in res:
res.append(node)
node=node.next
else:
return node.next
return None

LRU缓存机制(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class LRUCache(object):

def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.d = collections.OrderedDict()


def get(self, key):
"""
:type key: int
:rtype: int
"""
if key not in self.d:
return -1
res = self.d[key]
self.d.pop(key)
self.d[key]= res
return res


def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
if key not in self.d:
if self.capacity <= 0:
for k in self.d.keys():
self.d.pop(k)
break
else:
self.capacity-=1
else:
self.d.pop(key)
self.d[key]=value




# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)

排序链表(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# h_head = ListNode(None)
# print(h_head)
# res = []
# while head != None:
# res.append(head)
# head = head.next
# print(res)
# res = sorted(res,key = lambda x:x.val)
# print(res)
# n = len(res)
# h_head.next = res[0]
# # res[0].next = res[1]
# return h_head.next
# for i in range(n-1):
# res[i].next = res[i+1]
# return h_head.next


h_head = ListNode(None) #申请头节点
res = [] #将节点保存在列表中
while head is not None:
next_h = head.next
head.next = None
res.append(head)
head = next_h
# head = head.next
res = sorted(res,key = lambda x:x.val)
# print(res)
n = len(res)
if n == 0:
return None
h_head.next = res[0]
for i in range(n-1):
res[i].next = res[i+1]
# print(res)
return h_head.next

最小栈(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class MinStack(object):

def __init__(self):
"""
initialize your data structure here.
"""
self.l = [] #列表操作
self.index = -1


def push(self, x):
"""
:type x: int
:rtype: None
"""
# self.l.append(x)
# self.minnum = min(self.l)

self.l.append(x)
self.index+=1


def pop(self):
"""
:rtype: None
"""
self.l.pop()
# self.minnum =not self.l or min(self.l)
self.index-=1


def top(self):
"""
:rtype: int
"""
return self.l[-1]
# return self.l[self.index]


def getMin(self):
"""
:rtype: int
"""
# return self.minnum
return min(self.l)



# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

相交链表(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
l1=0
l2=0
node1=headA
node2=headB
while headA: #求第一个链表长度
l1+=1
headA=headA.next
while headB: #求第二个链表长度
l2+=1
headB=headB.next
s=l1-l2
while s>0: #对齐两个链表长度
node1=node1.next
s-=1
while s<0:
node2=node2.next
s+=1
while node1 and node2:
if node1==node2:
return node1
node1=node1.next
node2=node2.next
return None
# while node1!=node2: #从头开始判断地址是否相同
# node1=node1.next
# node2=node2.next
# return node1

多数元素(easy)

1
2
3
4
5
6
7
8
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = sorted(nums)
return res[(len(nums)//2)]

反转链表(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# if head:
# pre=head
# q=head.next
# while pre.next:
# pre.next=q.next
# q.next=head
# head=q
# q=pre.next
# return head
if head==None or head.next==None:
return head
pre=head
q=head.next
while pre.next:
pre.next=q.next
q.next=head
head=q
q=pre.next
return head

数组中的第K个最大元素(medium)

1
2
3
4
5
6
7
8
9
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
s = sorted(nums,reverse=True)
return s[k-1]

存在重复元素(easy)

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
d = dict(Counter(nums))
for v in d.values():
if v>=2:
return True
return False

二叉搜索树中第K小的元素(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
res = []

def pre(node):
if node == None:
return 0
pre(node.left)
res.append(node.val)
pre(node.right)
pre(root)
return res[k-1]
# print(res)

2的幂(easy)

1
2
3
4
5
6
7
8
9
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
else
if((n&n-1)==0)
return true;
else
return false;
}

二叉搜索树的最近公共祖先(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root==None or root==p or root==q:
return root
left = self.lowestCommonAncestor(root.left,p,q)
right= self.lowestCommonAncestor(root.right,p,q)
if left!=None and right!=None:
return root
if left!=None:
return left
if right!=None:
return right
return None

二叉树的最近公共祖先(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
#如果root不存在或者有一个值是根节点,直接返回根节点即可
if root == None or root==p or root==q:
return root
#递归左右子树查找
left = self.lowestCommonAncestor(root.left,p,q)
right = self.lowestCommonAncestor(root.right,p,q)
if left!=None and right != None:
return root
elif left!=None:
return left
elif right!=None:
return right
return None

删除链表中的节点(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val=node.next.val
node.next=node.next.next

除自身以外数组的乘积(medium)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res=[]
res1=[1 for i in range(len(nums))]
res2 = [1 for i in range(len(nums))]
for i in range(1,len(nums)):
res1[i]=nums[i-1]*res1[i-1]
for j in range(len(nums)-2,-1,-1):
res2[j]=nums[j+1]*res2[j+1]
for i in range(len(res1)):
res.append(res1[i]*res2[i])
return res
# print(res)
# for i in range(len(nums)):
# for j in range(i):
# res[i]*=nums[j]
# for k in range(i+1,len(nums)):
# res[i]*=nums[k]
# return res

Nim游戏(easy)

1
2
3
4
5
6
bool canWinNim(int n) {
if(n%4!=0)
return true;
else
return false;
}

反转字符串(easy)

1
2
3
4
5
6
7
8
9
10
void reverseString(char* s, int sSize) {
int temp;
int i;
for(i=0;i<sSize/2;i++){
temp=s[i];
s[i]=s[sSize-i-1];
s[sSize-i-1]=temp;
}
return s;
}

反转字符串中的单词III(easy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return " ".join(i[::-1] for i in s.split())

# res = ""
# s1 = list(s.split(" "))
# for i in range(len(s1)-1):
# res+=s1[i][::-1]
# res+=" "
# res+=s1[-1][::-1]
# return res