20190130:被疫情困在家里,没事刷刷剑指offer的题目,这里写一个题解合集,还没更完,搞定15道
20190206:28道啦
20190211:46道
20190215:61道
20190216:全部更完
# -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
for i, m in enumerate(numbers):
if i == m:
continue
else:
if numbers[m] == m:
duplication[0] = m
return True
else:
numbers[i] = numbers[m]
numbers[m] = m
return False
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
i = len(array) - 1
j = 0
while i!=0 or j != len(array[0]) - 1:
if i < 0 or j > len(array[0]) - 1:
return False
n = array[i][j]
if n > target:
i -= 1
elif n < target:
j += 1
else:
return True
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
s = s.replace(' ', '%20')
return s
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
re = []
while listNode:
re.append(listNode.val)
listNode = listNode.next
return re[::-1]
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if len(pre) == 0:
return None
root_val = pre[0]
root = TreeNode(root_val)
idx = tin.index(root_val)
if idx == 0:
left_tree = None
else:
left_tree = self.reConstructBinaryTree(pre[1:idx+1], tin[:idx])
if idx == len(pre) - 1:
right_tree = None
else:
right_tree = self.reConstructBinaryTree(pre[idx+1:], tin[idx+1:])
root.left = left_tree
root.right = right_tree
return root
# -*- coding:utf-8 -*-
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
def GetNext(self, pNode):
# write code here
if pNode.right:
pNode = pNode.right
while pNode.left:
pNode = pNode.left
return pNode
while pNode:
if pNode.next:
if pNode.next.left == pNode:
return pNode.next
pNode = pNode.next
else:
return None
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
# write code here
while self.stack2:
self.stack1.append(self.stack2.pop())
self.stack1.append(node)
def pop(self):
# return xx
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
if n <= 0:
return 0
if n == 1:
return 1
i = 2
a, b = 0, 1
while i <= n:
s = a + b
a, b = b, s
i += 1
return s
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
if not rotateArray:
return 0
left = 0
right = len(rotateArray) - 1
while left < right:
if rotateArray[left]<rotateArray[right]:
return rotateArray[left]
mid = (right + left) // 2
if rotateArray[left] < rotateArray[mid]:
left = mid
elif rotateArray[mid] > rotateArray[right]:
right = mid
else:
right -= 1
return rotateArray[mid+1]
# -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
for i in range(len(matrix)):
if matrix[i] == path[0]:
if self.isPath(matrix, rows, cols, i, path):
return True
return False
def isPath(self, matrix, rows, cols, i, path):
if matrix[i] != path[0]:
return False
if len(path) == 1:
return True
# 可以设置一个矩阵,来标志某一格子是否已经被走过
matrix = matrix[:i] + '#' + matrix[i+1:]
up = self.isPath(matrix, rows, cols, i-cols, path[1:]) if i >= cols else False
down = self.isPath(matrix, rows, cols, i+cols, path[1:]) if i < len(matrix) - cols else False
right = self.isPath(matrix, rows, cols, i+1, path[1:]) if ((i+1) % cols != cols and i+1 < len(matrix)) else False
left = self.isPath(matrix, rows, cols, i-1, path[1:]) if (i % cols != cols and i-1>0) else False
return up or down or left or right
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
return len(self.spaceCount(set(), 0, 0, threshold, rows, cols))
def spaceCount(self, re, i, j, threshold, rows, cols):
if self.get_bitsum(i) + self.get_bitsum(j) > threshold or (i, j) in re:
return re
re.add((i,j))
if i + 1 < rows:
re = self.spaceCount(re, i+1, j, threshold, rows, cols)
if j + 1 < cols:
re = self.spaceCount(re, i, j+1, threshold, rows, cols)
return re
def get_bitsum(self, num):
s = 0
while num>0:
s += num % 10
num = num // 10
return s
# -*- coding:utf-8 -*-
class Solution:
def cutRope(self, number):
# write code here
if number < 2: return 0
if number == 2:return 1
if number == 3:return 2
products = [0, 1, 2, 3]
for i in range(4, number+1, 1):
product = 0
for j in range(1,i//2+1):
res = products[j]* products[i-j]
product = max(res,product)
products.append(product)
return products[-1]
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1(self, n):
# write code here
count=0
if n < 0:
n = n & 0xffffffff
while n!=0:
n=n&(n-1)
count+=1
return count
解法一:
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
return self.PosPower(base, exponent) if exponent >= 0 else 1 / self.PosPower(base, -exponent)
def PosPower(self, base, exponent):
re = 1
for i in range(exponent):
re *= base
return re
解法二:
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
return self.PosPower(base, exponent) if exponent >= 0 else 1 / self.PosPower(base, -exponent)
def PosPower(self, base, exponent):
if exponent == 0:
return 1
if exponent == 1:
return base
re_half = self.PosPower(base, exponent//2)
if exponent % 2 == 0:
re = re_half * re_half
else:
re = re_half * re_half * base
return re
解法一:
n = 3
def strAdd1(number):
length = len(number)
for i in range(length):
n = ord(number[-i-1]) - ord('0')
if n != 9:
bit = chr(n+1+ord('0'))
number = number[:-i-1] + bit + ''.join(['0']*i)
return number
return '1' + ''.join(['0']*length)
number = '0'
last_number = ''.join(['9']*n)
print(number)
while number != last_number:
number = strAdd1(number)
print(number)
解法二:
n = 3
def printN(pre, length):
if length == 0:
print(pre)
return
for i in range(10):
printN(pre+str(i), length-1)
return
for i in range(n):
if i == 0:
printN('', i + 1)
else:
for j in range(1,10):
printN(str(j), i)
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
def deleteHeadDuplication(pHead):
while pHead.next.val == pHead.val:
pHead.next = pHead.next.next
if not pHead.next:
return None
return pHead.next
if not pHead or not pHead.next:
return pHead
re = ListNode(0)
re.next = pHead
cur = re
while cur.next and cur.next.next:
if cur.next.val == cur.next.next.val:
cur.next = deleteHeadDuplication(cur.next)
else:
cur = cur.next
return re.next
# -*- coding:utf-8 -*-
class Solution:
# s, pattern都是字符串
def match(self, s, pattern):
# 如果s与pattern都为空,则True
if len(s) == 0 and len(pattern) == 0:
return True
# 如果s不为空,而pattern为空,则False
elif len(s) != 0 and len(pattern) == 0:
return False
# 如果s为空,而pattern不为空,则需要判断
elif len(s) == 0 and len(pattern) != 0:
# pattern中的第二个字符为*,则pattern后移两位继续比较
if len(pattern) > 1 and pattern[1] == '*':
return self.match(s, pattern[2:])
else:
return False
# s与pattern都不为空的情况
else:
# pattern的第二个字符为*的情况
if len(pattern) > 1 and pattern[1] == '*':
# s与pattern的第一个元素不同,则s不变,pattern后移两位,相当于pattern前两位当成空
if s[0] != pattern[0] and pattern[0] != '.':
return self.match(s, pattern[2:])
else:
# 如果s[0]与pattern[0]相同,且pattern[1]为*,这个时候有三种情况
# pattern后移2个,s不变;相当于把pattern前两位当成空,匹配后面的
# pattern后移2个,s后移1个;相当于pattern前两位与s[0]匹配
# pattern不变,s后移1个;相当于pattern前两位,与s中的多位进行匹配,因为*可以匹配多位
return self.match(s, pattern[2:]) or self.match(s[1:], pattern[2:]) or self.match(s[1:], pattern)
# pattern第二个字符不为*的情况
else:
if s[0] == pattern[0] or pattern[0] == '.':
return self.match(s[1:], pattern[1:])
else:
return False
# -*- coding:utf-8 -*-
import re
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
return re.match(r"^[\+\-]?[0-9]*(\.[0-9]*)?([eE][\+\-]?[0-9]+)?$",s)
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
return sorted(array,key=lambda c:c%2,reverse=True)
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindKthToTail(self, head, k):
# write code here
if not head or k <= 0:
return None
fast = head
slow = head
for i in range(k):
if not fast:
return None
fast = fast.next
while fast:
slow = slow.next
fast = fast.next
return slow
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
# 判断是否有环
def hasCycle(head):
slow = head
fast = head
i = 0
while fast:
fast = fast.next
if i % 2 != 0:
slow = slow.next
if fast == slow:
return True, fast
i += 1
return False, None
# 无环则返None
hasCycle, cyclePoint = hasCycle(head)
if not hasCycle:
return None
# 计算环的周长l
count = 1
cur = cyclePoint.next
while cur != cyclePoint:
cur = cur.next
count += 1
# 后一个指针移动l步
cur = head
for i in range(count):
cur = cur.next
# 前后指针同步移动,找到环的入口
count = 0
while head != cur:
head = head.next
cur = cur.next
count += 1
return head
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
def ReverseAndTail(pHead):
if not pHead.next:
return pHead, pHead
pAfter, tail = ReverseAndTail(pHead.next)
pHead.next = None
tail.next = pHead
return pAfter, pHead
if not pHead:
return None
else:
pHead, _ = ReverseAndTail(pHead)
return pHead
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
if not pHead1:
return pHead2
if not pHead2:
return pHead1
re = ListNode(0) # 添加一个哨兵节点
re.next = pHead1
pHead1 = re
temp = ListNode(0) # 使用temp变量保存要插入的节点
while pHead1.next:
if pHead2.val <= pHead1.next.val:
temp.next = pHead2 # 使用temp变量保存要插入的节点
pHead2 = pHead2.next
temp.next.next = pHead1.next # 修改插入节点的指针
pHead1.next = temp.next # 将插入节点插进去
pHead1 = pHead1.next
if not pHead2: # 若链表2全部插入链表1
break
if pHead2: # 若链表2未全部插入链表1
pHead1.next = pHead2
return re.next
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
# 判断pRoot2是否为pRoot1同根的子树
def IsSameRootTree(pRoot1, pRoot2):
if not pRoot2: # 判断pRoot2是否已经匹配完
return True
if not pRoot1: # 若pRoot2未匹配完,而pRoot1已经匹配完了,则返回False
return False
return pRoot1.val == pRoot2.val and IsSameRootTree(pRoot1.left, pRoot2.left) and IsSameRootTree(pRoot1.right, pRoot2.right)
if not pRoot1 or not pRoot2:
return False
return IsSameRootTree(pRoot1, pRoot2) or self.HasSubtree(pRoot1.left, pRoot2) or self.HasSubtree(pRoot1.right, pRoot2)
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
# write code here
if not root:
return root
root.left, root.right = self.Mirror(root.right), self.Mirror(root.left)
return root
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetrical(self, pRoot):
# write code here
if not pRoot:
return True
return self.isMirror(pRoot.left, pRoot.right)
def isMirror(self, left, right):
if not left and not right:
return True
elif left and right:
center = self.isMirror(left.right, right.left)
side = self.isMirror(left.left, right.right)
return center and side and left.val == right.val
else:
return False
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
rows = len(matrix)
cols = len(matrix[0])
if rows == 0:
return []
re = []
i = 0
while True:
if i > rows - i - 1 or i > cols - i - 1:
break
if i == rows - i - 1:
re += matrix[i][i:cols - i]
break
if i == cols - i - 1:
re += [x[i] for x in matrix[i:rows - i]]
break
# if i + 1 == rows - i - 1:
# re += matrix[i][i:i + 2] + matrix[i + 1][i:i + 2][::-1]
# break
re += matrix[i][i:cols - i]
re += [x[cols - i - 1] for x in matrix[i + 1:rows - i - 1]]
re += matrix[rows - i - 1][i:cols - i][::-1]
re += [x[i] for x in matrix[i + 1:rows - i - 1]][::-1]
i += 1
return re
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
self.assist_stack = []
def push(self, node):
# write code here
self.stack.append(node)
if not self.assist_stack:
self.assist_stack.append(node)
else:
if node <= self.assist_stack[-1]:
self.assist_stack.append(node)
return
def pop(self):
# write code here
if self.stack:
if self.stack[-1] == self.assist_stack[-1]:
self.assist_stack.pop()
return self.stack.pop()
else:
return None
def top(self):
# write code here
if self.stack:
return self.stack[-1]
else:
return None
def min(self):
# write code here
if not self.assist_stack:
return None
return self.assist_stack[-1]
# -*- coding:utf-8 -*-
class Solution:
def IsPopOrder(self, pushV, popV):
# write code here
if sorted(pushV) != sorted(popV):
return False
stack = []
re = []
i = 0
while i < len(popV):
if not pushV and stack:
return False
if not stack or stack[-1] != popV[i]:
stack += pushV[:pushV.index(popV[i]) + 1]
pushV = pushV[pushV.index(popV[i]) + 1:]
while stack and stack[-1] == popV[i]:
re.append(stack.pop())
i += 1
return re == popV
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
if not root:
return []
re = []
queue = [root]
while queue:
tree = queue.pop(0)
re.append(tree.val)
if tree.left:
queue.append(tree.left)
if tree.right:
queue.append(tree.right)
return re
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if not sequence:
return False
# 找到左右子树的分割点
i = 0
while sequence[i] < sequence[-1]:
i += 1
# 检查左树是否BST
if i == 0:
left_BST = True
else:
left_BST = self.VerifySquenceOfBST(sequence[:i])
# 检查右树是否BST,且都大于根节点
if i == len(sequence) - 1:
right_BST = True
elif min(sequence[i:-1]) < sequence[-1]:
right_BST = False
else:
right_BST = self.VerifySquenceOfBST(sequence[i:-1])
# 返回节点
return True if left_BST and right_BST else False
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
re = []
paths = self.FindPathSum(root)
for path in paths:
if sum(path) == expectNumber:
re.append(path)
return re
def FindPathSum(self, root):
if not root:
return []
if not root.left and not root.right:
return [[root.val]]
re = []
leftSum = self.FindPathSum(root.left)
rightSum = self.FindPathSum(root.right)
while leftSum and rightSum:
if len(leftSum[0]) > len(rightSum[0]):
re.append([root.val] + leftSum[0])
leftSum.pop(0)
else:
re.append([root.val] + rightSum[0])
rightSum.pop(0)
if leftSum:
re += [[root.val] + x for x in leftSum]
elif rightSum:
re += [[root.val] + x for x in rightSum]
return re
# -*- coding:utf-8 -*-
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
def CloneNode(pHead):
cur = pHead
while cur:
newNode = RandomListNode(cur.label)
newNode.next = cur.next
cur.next = newNode
cur = newNode.next
return pHead
def CloneRandom(pHead):
cur = pHead
while cur:
if cur.random:
cur.next.random = cur.random.next
cur = cur.next.next
return pHead
def Split(pHead):
cur_org = pHead
cur_new = pHead.next
pHead_new = pHead.next
while cur_new.next:
cur_org.next = cur_org.next.next
cur_new.next = cur_new.next.next
cur_org = cur_org.next
cur_new = cur_new.next
cur_org.next = None
return pHead_new
if not pHead:
return None
pHead = CloneNode(pHead)
pHead = CloneRandom(pHead)
pHead_new = Split(pHead)
return pHead_new
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return None
if pRootOfTree.left:
left_node = self.Convert(pRootOfTree.left)
while left_node.right:
left_node = left_node.right
left_node.right = pRootOfTree
pRootOfTree.left = left_node
if pRootOfTree.right:
right_node = self.Convert(pRootOfTree.right)
right_node.left = pRootOfTree
pRootOfTree.right = right_node
while pRootOfTree.left:
pRootOfTree = pRootOfTree.left
return pRootOfTree
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# shiyong前序遍历的思路
def Serialize(self, root):
# write code here
if not root:
return '$'
s = str(root.val)
left = self.Serialize(root.left)
right = self.Serialize(root.right)
return s + ',' + left + ',' + right
def Deserialize(self, s):
# write code here
def DeserialStr(l):
if l[0] == '$':
return None, l[1:]
root = TreeNode(int(l[0]))
l = l[1:]
left, l = DeserialStr(l)
right, l = DeserialStr(l)
root.left = left
root.right = right
return root, l
l = s.split(',')
root, s = DeserialStr(l)
return root
# -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
# write code here
if len(ss) == 1:
return ss
re = []
for i in range(len(ss)):
after = self.Permutation(ss[:i]+ss[i+1:])
re += [ss[i] + x for x in after]
res = []
for r in re:
if r not in res:
res.append(r)
res.sort(key=lambda x:ord(x[0]))
return res
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
hashmap = {}
for num in numbers:
if num in hashmap:
hashmap[num] += 1
else:
hashmap[num] = 1
half_length = 0.5 * len(numbers)
for k,v in hashmap.items():
if v > half_length:
return k
return 0
# -*- coding:utf-8 -*-
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
if k > len(tinput):
return []
if k == len(tinput):
return sorted(tinput)
start, end = 0, len(tinput) - 1
while True:
tinput, pivot_idx = self.Partition(tinput, start, end, k)
if pivot_idx == k:
return sorted(tinput[0:k])
elif pivot_idx > k:
end = pivot_idx - 1
else:
start = pivot_idx + 1
def Partition(self, nums, start, end, pivot_idx):
# pivot置于最后
nums[pivot_idx], nums[end] = nums[end], nums[pivot_idx]
# 进行交换
pivot = nums[end]
store_idx = start
for i in range(start, end):
if nums[i] < pivot:
nums[store_idx], nums[i] = nums[i], nums[store_idx]
store_idx += 1
# 把pivot换回来
nums[store_idx], nums[end] = nums[end], nums[store_idx]
return nums, store_idx
# -*- coding:utf-8 -*-
from heapq import *
class Solution:
def __init__(self):
self.heaps = [], []
self.even = True
def Insert(self, num):
# write code here
small, large = self.heaps
heappush(large, -heappushpop(small, num))
self.even = not self.even
if self.even: # if even,即已有数据是偶数个,且large比small多两个
heappush(small, -heappop(large))
def GetMedian(self,ss):
# write code here
small, large = self.heaps
return 0.5 * (small[0]-large[0]) if self.even else -large[0]
# --看一下书上的动态规划思路--
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
n = len(nums)
curr_sum = max_sum = nums[0]
for i in range(1, n):
curr_sum = max(nums[i], curr_sum + nums[i])
max_sum = max(max_sum, curr_sum)
return max_sum
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
sum = 0
for num in range(1, n+1):
while(num):
if num % 10 == 1:
sum += 1
num = num // 10
return sum
def getBitNumber(n):
counts = [0]
i = 1
while True:
count = 10 ** i - sum(counts)
if n > count * i:
n -= count * i
else:
break
counts.append(count)
i += 1
num = n // i + sum(counts)
bit = n % i
return str(num)[bit]
print(getBitNumber(1001))
# -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
# 判断sa是否比sb小
def IsSmaller(sa, sb):
sab = sa + sb
sba = sb + sa
for i in range(len(sab)):
if sab[i] < sba[i]:
return True
elif sab[i] > sba[i]:
return False
return True
# 二分法
def Partition(numbers, start, end):
if start >= end:
return numbers
store_idx = start
for i in range(start, end):
if IsSmaller(numbers[i], numbers[end]):
numbers[store_idx], numbers[i] = numbers[i], numbers[store_idx]
store_idx += 1
numbers[store_idx], numbers[end] = numbers[end], numbers[store_idx]
numbers = Partition(numbers, start, store_idx - 1)
numbers = Partition(numbers, store_idx + 1, end)
return numbers
numbers = [str(x) for x in numbers]
numbers = Partition(numbers, 0, len(numbers)-1)
re = ''
for n in numbers:
re += n
return re
def Possibilities(str):
num = int(str)
return 1 if num >= 10 and num <= 25 else 0
def Number2Str(num):
num = str(num)
if len(num) == 0:
return 0
if len(num) == 1:
return 1
trans = [0] * len(num)
trans[0] = 1
trans[1] = Possibilities(num[0:2]) + 1
for i in range(2, len(num)):
trans[i] = trans[i-2] * Possibilities(num[i-1:i+1]) + trans[i-1]
return trans[-1]
Number2Str(12258)
def MaxValue(value):
if not value:
return 0
m = len(value)
n = len(value[0])
value_sum = [[0] * n for x in range(m)] # 这里注意,不能使用[[0] * n] * m,这是因为创建的m个list指向相同地址
for i in range(m):
for j in range(n):
up_sum = 0 if i == 0 else value_sum[i-1][j]
left_sum = 0 if j == 0 else value_sum[i][j-1]
value_sum[i][j] = max(up_sum, left_sum) + value[i][j]
return value_sum[m-1][n-1]
value = [[1,10,3,8], [12,2,9,6], [5,7,4,11], [3,7,16,5]]
MaxValue(value)
def MaxUnrepeat(str):
if not str:
return 0
store26 = [-1] * 26
store_unrepeat = [0] * len(str)
for i in range(len(str)):
if i == 0:
store_unrepeat[i] = 1
c = str[i]
idx = ord(c) - ord('a')
if i - store26[idx] > store_unrepeat[i - 1] or store26[idx] == -1:
store_unrepeat[i] = store_unrepeat[i-1] + 1
else:
store_unrepeat[i] = i - store26[idx]
store26[idx] = i
return max(store_unrepeat)
MaxUnrepeat('arabcacfr')
# -*- coding:utf-8 -*-
class Solution:
def GetUglyNumber_Solution(self, index):
def UpdateIdxM(idx, uglys, i, factor):
while uglys[idx] * factor <= uglys[i - 1]:
idx += 1
return idx, uglys[idx] * factor
if index == 0:
return 0
if index == 1:
return 1
uglys = [0] * index
uglys[0] = 1
idx2, idx3, idx5 = 0, 0, 0
for i in range(1, index):
idx2, m2 = UpdateIdxM(idx2, uglys, i, 2)
idx3, m3 = UpdateIdxM(idx3, uglys, i, 3)
idx5, m5 = UpdateIdxM(idx5, uglys, i, 5)
uglys[i] = min([m2, m3, m5])
return uglys[-1]
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
early2late = []
hashmap = {}
for i in range(len(s)):
if s[i] not in early2late:
early2late.append(s[i])
hashmap[s[i]] = i + 1
else:
hashmap[s[i]] = -1
for c in early2late:
idx = hashmap[c]
if idx > 0:
return idx - 1
return -1
# -*- coding:utf-8 -*-
class Solution:
def InversePairs(self, data):
# 时间复杂度nlogn,和归并法一样
# 二分查找
def Partition(numbers, num):
left = 0
right = len(numbers) - 1
while left <= right:
mid = int(0.5 * (left + right))
if numbers[mid] > num:
right = mid-1
else:
if mid == len(numbers) - 1 or numbers[mid+1] > num:
return mid
else:
left = mid + 1
return -1
# 维护一个有序的数组,每次插入一个数字,并找出已排序数组中,比它大的个数
sorted_data = []
sum = 0
for num in data:
idx = Partition(sorted_data, num)
sum += len(sorted_data) - idx - 1
sorted_data.insert(idx + 1, num)
return sum % 1000000007
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
if pHead1 == pHead2:
return pHead1
stack1 = []
stack2 = []
while pHead1:
stack1.append(pHead1)
pHead1 = pHead1.next
while pHead2:
stack2.append(pHead2)
pHead2 = pHead2.next
while stack1 and stack2:
cur1 = stack1.pop()
cur2 = stack2.pop()
if cur1 == cur2:
continue
else:
return cur1.next
if not stack1 and not stack2:
return None
if not stack1:
return stack2[-1].next
if not stack2:
return stack1[-1].next
# -*- coding:utf-8 -*-
class Solution:
def GetNumberOfK(self, data, k):
# write code here
idx_start = self.SearchFirst(data, 0, len(data)-1, k)
if idx_start == -1:
return 0
idx_end = self.SearchLast(data, 0, len(data)-1, k)
return idx_end - idx_start + 1
# 查找第一个等于target的元素
# 找到 —— 返回索引,找不到 —— 返回-1
def SearchFirst(self, array, left, right, target):
while left <= right:
mid = left + int(0.5 * (right - left))
if array[mid] < target:
left = mid + 1
elif array[mid] > target:
right = mid - 1
else:
if mid == left or array[mid-1] != target:
return mid
else:
right = mid - 1
return -1
# 查找最后一个等于target的元素
# 找到 —— 返回索引,找不到 —— 返回-1
def SearchLast(self, array, left, right, target):
while left <= right:
mid = left + int(0.5 * (right - left))
if array[mid] < target:
left = mid + 1
elif array[mid] > target:
right = mid - 1
else:
if mid == right or array[mid+1] != target:
return mid
else:
left = mid + 1
return -1
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
# write code here
def GetSorted(pRoot):
if not pRoot:
return []
left = GetSorted(pRoot.left)
right = GetSorted(pRoot.right)
return left + [pRoot] + right
if k <= 0:
return None
sorted_tree = GetSorted(pRoot)
if k > len(sorted_tree):
return None
return sorted_tree[k-1]
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeDepth(self, pRoot):
# write code here
if not pRoot:
return 0
return max(self.TreeDepth(pRoot.left), self.TreeDepth(pRoot.right)) + 1
# -*- coding:utf-8 -*-
class Solution:
def FindNumsAppearOnce(self, array):
if not array:
return []
# 对array中的数字进行异或运算
tmp = 0
for i in array:
tmp ^= i
# 获取tmp中最低位1的位置
idx = 0
while (tmp & 1) == 0:
tmp >>= 1
idx += 1
# 分成两组计算异或
a = b = 0
for i in array:
if (i >> idx) & 1:
a ^= i
else:
b ^= i
return [a, b]
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
i = 0
j = len(array) - 1
n_min = -1
n_max = -1
product = 0
while i < j:
s = array[i] + array[j]
if s < tsum:
i += 1
elif s > tsum:
j -= 1
else:
if array[i] * array[j] < product or n_min == -1:
n_min = array[i]
n_max = array[j]
product = n_min * n_max
i += 1
if n_max == -1:
return []
else:
return n_min, n_max
# -*- coding:utf-8 -*-
class Solution:
def ReverseSentence(self, s):
# write code here
word_list = s.split(' ')
re = ''
while word_list:
re += ' ' + word_list.pop()
return re[1:]
# -*- coding:utf-8 -*-
class Solution:
def maxInWindows(self, num, size):
# write code here
if size == 0:
return []
queue,res,i = [],[],0
for i in range(len(num)):
if len(queue)>0 and i-size+1 > queue[0]: #若最大值queue[0]位置过期 则弹出
queue.pop(0)
while len(queue)>0 and num[queue[-1]]<num[i]: #弹出所有比num[i]小的数字
queue.pop()
queue.append(i)
if i >= size-1: # 从第size个位置,开始输出
res.append(num[queue[0]])
return res
n = 2
s = 2
for i in range(n):
store = [0] * 6 * (i+1)
if i == 0:
store = [1] * 6
store_pre = store
else:
for j in range(i, 6*(i+1)):
store[j] = sum(store_pre[:j]) if j < 6 else sum(store_pre[j-6:j])
store_pre = store
# print(store)
print(store[s-1]/6**n)
# -*- coding:utf-8 -*-
class Solution:
def IsContinuous(self, numbers):
# write code here
if len(numbers) != 5:
return False
numbers.sort()
count0 = 0
for i in range(len(numbers)):
if numbers[i] == 0:
count0 += 1
else:
start = i
break
if numbers[start] < 1 or numbers[-1] > 13:
return False
for i in range(start, len(numbers) - 1): # 判断有无重复的牌
if numbers[i] == numbers[i+1]:
return False
if count0 >= (numbers[-1] - numbers[start] - 1) - (len(numbers) - start - 2):
return True
else:
return False
# -*- coding:utf-8 -*-
class Solution:
def LastRemaining_Solution(self, n, m):
# write code here
if n < 1 or m < 1:
return -1
last = 0
for i in range(2, n+1):
last = (last+m)%i
return last
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
low = 0
profit = 0
for i, price in enumerate(prices):
if price < prices[low]:
low = i
elif price > prices[low]:
profit = max(profit, price - prices[low])
else:
continue
return profit
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
# python的a and b, a == False 则取a, 否则取b
return n and (n + self.Sum_Solution(n - 1))
# -*- coding:utf-8 -*-
class Solution:
def Add(self, num1, num2):
# write code here
# 由于题目要求不能使用四则运算,那么就需要考虑使用位运算
# 两个数相加可以看成两个数的每个位先相加,但不进位,然后在加上进位的数值
# 如12+8可以看成1+0=1 2+8=0,由于2+8有进位,所以结果就是10+10=20
# 二进制中可以表示为1000+1100 先每个位置相加不进位,
# 则0+0=0 0+1=1 1+0=1 1+1=0这个就是按位异或运算
# 对于1+1出现进位,我们可以使用按位与运算然后在将结果左移一位
# 最后将上面两步的结果相加,相加的时候依然要考虑进位的情况,直到不产生进位
# 注意python没有无符号右移操作,所以需要越界检查
# 按位与运算:相同位的两个数字都为1,则为1;若有一个不为1,则为0。
# 按位异或运算:相同位不同则为1,相同则为0。
while num2:
result = (num1 ^ num2) & 0xffffffff
carry = ((num1 & num2) << 1) & 0xffffffff
num1 = result
num2 = carry
if num1 <= 0x7fffffff:
result = num1
else:
result = ~(num1^0xffffffff)
return result
a = [4,6,2,4,8,3,4]
length = len(a)
before, after = [1] * length, [1] * length
for i in range(1,length):
before[i] = before[i-1] * a[i-1]
after[length-i-1] = after[length-i] * a[length-i]
re = [before[i]*after[i] for i in range(length)]
print(re)