import collections
class Solution(object):
def CheckPermutation(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
freq = collections.Counter(s1)
for i in range(len(s2)):
freq[s2[i]] -= 1
for k,v in freq.items():
if v != 0 :
return False
return True
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return
left = 0
right = len(nums) - 1
mid = left + (right-left) // 2
tree = TreeNode(nums[mid])
tree.left = self.sortedArrayToBST(nums[:mid])
tree.right = self.sortedArrayToBST(nums[mid+1:])
return tree
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [0] * len(nums)
dp[0] = nums[0]
max_dp = dp[0]
for i in range(1,len(nums)):
dp[i] = max((dp[i-1] + nums[i]),nums[i])
max_dp = max(max_dp,dp[i])
return max_dp
import collections
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
freq = collections.Counter(nums)
for num in range(len(nums)+1):
if num not in freq:
return num
import collections
class Solution(object):
def canPermutePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
freq = collections.Counter(s)
prior = 1
for k,v in freq.items():
if freq[k] % 2 == 0:
continue
else:
prior -= 1
return prior >= 0
class Solution(object):
def arraysIntersection(self, arr1, arr2,arr3):
def cross(arr1,arr2):
i, j = 0, 0
res = []
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
i += 1
elif arr1[i] > arr2[j]:
j += 1
else:
res.append(arr1[i])
i += 1
j += 1
return res
temp = cross(arr1,arr2)
res = cross(temp,arr3)
return res
class Solution(object):
def longestOnes(self, nums, k):
i,j = 0,0
z_cnt = k
res = -1
while j < len(nums):
if nums[j] == 0: z_cnt -= 1
while z_cnt < 0:
if nums[i] == 0:
z_cnt += 1
i += 1
res = max(res,(j-i+1))
j += 1
return res
class Solution:
def fourSum(self, nums,target):
quadruplets = list()
if not nums or len(nums) < 4:
return quadruplets
nums.sort()
length = len(nums)
for i in range(length - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, length - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
left, right = j + 1, length - 1
while left < right:
total = nums[i] + nums[j] + nums[left] + nums[right]
if total == target:
quadruplets.append([nums[i], nums[j], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
right -= 1
elif total < target:
left += 1
else:
right -= 1
return quadruplets
class Solution(object):
def longestPalindrome(self, s):
if not s or len(s) == 1:
return s
max_len = 1
res = s[0]
for i in range(1,len(s)):
left ,right = i,i
while left > 0 and s[left-1] == s[i]:
left -= 1
while right < len(s) - 1 and s[right+1] == s[i]:
right += 1
while left > 0 and right < len(s)-1 and s[left-1] == s[right+1]:
left -= 1
right += 1
if max_len < (right - left + 1):
max_len = right - left + 1
res = s[left:left+max_len]
return res
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) == 1: return True
max_steps = 0
i = 0
while i <= max_steps:
if i + nums[i] > max_steps:
max_steps = i + nums[i]
if max_steps >= len(nums) - 1:
return True
i += 1
return False
class Solution(object):
def jump(self, nums):
start = 0
end = 1
ans = 0
while end < len(nums):
max_pos = 0
for i in range(start,end):
max_pos = max(max_pos,i + nums[i])
start = end
end = max_pos + 1
ans += 1
return ans
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
"""
dummy = ListNode(-1)
pre = dummy
high = 0
while l1 and l2:
val = (l1.val + l2.val + high) % 10
high = (l1.val + l2.val + high) // 10
node = ListNode(val)
pre.next = node
pre = pre.next
l1 = l1.next
l2 = l2.next
while l1:
val = (l1.val + high) % 10
high = (l1.val + high) // 10
node = ListNode(val)
pre.next = node
pre = pre.next
l1 = l1.next
while l2:
val = (l2.val + high) % 10
high = (l2.val + high) // 10
node = ListNode(val)
pre.next = node
pre = pre.next
l2 = l2.next
if high:
pre.next = ListNode(high)
return dummy.next
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
i,j = 0,0
max_len = 0
for i in range(len(s)):
j = i
temp = set()
while j < len(s) and s[j] not in temp:
temp.add(s[j])
j += 1
max_len = max(max_len,j-i)
return max_len
class Solution(object):
def lengthOfLongestSubstring(self, s):
left = 0
right = 0
max_len = 0
temp = []
while right < len(s):
if s[right] not in temp:
temp.append(s[right])
else:
while s[left] != s[right]:
temp.remove(s[left])
left += 1
temp.remove(s[left])
left += 1
temp.append(s[right])
max_len = max(max_len,right - left + 1)
right += 1
return max_len
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
i,j = 0,0
max_len = 0
while j < len(s):
while j < len(s) and len(set(s[i:j+1])) == len(s[i:j+1]): j+= 1
max_len = max(max_len,j-i)
i += 1
return max_len
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
i = 0
j = 0
max_len = 0
while j <= len(s) - 1:
if len(set(s[i:j+1])) == j - i + 1:
max_len = max(max_len,(j-i+1))
j += 1
if len(set(s[i:j+1])) != j - i + 1:
i += 1
return max_len
class Solution(object):
def findNumberIn2DArray(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
i = len(matrix) - 1
j = 0
while i >= 0 and j < len(matrix[0]):
if matrix[i][j] < target: j += 1
elif matrix[i][j] > target: i -=1
else:
return True
return False
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
new = 0
fuhaofu = 0
if x < 0:
x = - x
fuhaofu = 1
while x :
yu = x % 10
x = x // 10
new = new * 10 + yu
if fuhaofu:
new = - new
if new < - 2**31 or new > 2**31 - 1:
return 0
return new
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0 : return False
x = str(x)
i = 0
j = len(x) - 1
while i < j :
if x[i] == x[j]:
i += 1
j -= 1
else:
return False
return True
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_num = -9999
dp = [0] * len(nums)
for i in range(len(nums)):
dp[i] = max(dp[i-1] + nums[i],nums[i])
max_num = max(max_num,dp[i])
return max_num
class Solution(object):
def minArray(self, numbers):
"""
:type numbers: List[int]
:rtype: int
"""
left = 0
right = len(numbers) - 1
while left < right:
mid = left + (right - left) // 2
if numbers[mid] > numbers[right]:
left = mid + 1
elif numbers[mid] < numbers[right]:
right = mid
else:
right -= 1
return numbers[left]
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return 0
slow,fast = 1,1
while fast < len(nums):
if nums[fast] != nums[fast-1]:
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
n = len(nums)
def helper(i,temp):
res.append(temp)
for j in range(i,n):
helper(j+1,temp+[nums[j]])
helper(0,[])
return res
class Solution(object):
def findContinuousSequence(self, target):
"""
:type target: int
:rtype: List[List[int]]
"""
i,j = 1,1
res = []
while i <= target//2:
temp_sum = sum(range(i,j))
if temp_sum < target:
j += 1
elif temp_sum > target:
i += 1
else:
res.append(list(range(i,j)))
i += 1
return res
class Solution(object):
def findContinuousSequence(self, target):
"""
:type target: int
:rtype: List[List[int]]
"""
left = 1
right = 1
res = []
while right <= target//2 + 1:
summ = sum(range(left,right+1))
if summ < target : right += 1
elif summ > target : left += 1
else:
res.append(list(range(left,right+1)))
left += 1
right += 1
return res
class Solution(object):
def isStraight(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
nums = sorted(nums)
vote = 1
min_num = 999
for num in nums:
if num != 0:
min_num = num
break
for i in range(1,len(nums)):
if nums[i] == nums[i-1] and nums[i-1] != 0: return False
if nums[i] != nums[i-1] or nums[i-1] == 0:
vote += 1
return max(nums) - min_num < vote
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def is_mirror(p,q):
if not p and not q : return True
if not p and q or not q and p or p.val != q.val: return False
return is_mirror(p.left,q.right) and is_mirror(p.right,q.left)
return is_mirror(root,root)
class Solution(object):
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
i = 0
max_len = 0
for i in range(len(s)):
j = i
temp = set()
while j < len(s):
temp.add(s[j])
if len(temp) <= 2:
j += 1
else:
break
max_len = max(max_len,j-i)
return max_len
class Solution(object):
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
i,j = 0,0
max_len = 0
while j < len(s):
while j < len(s) and len(set(s[i:j+1])) <= 2 : j += 1
max_len = max(max_len,j-i)
i += 1
return max_len
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dp = [0] + [10001] * amount
for coin in coins:
for j in range(coin,amount+1):
dp[j] = min(dp[j],dp[j-coin]+1)
return dp[-1] if dp[-1] != 10001 else -1
class Solution(object):
def mincostTickets(self, days, costs):
"""
:type days: List[int]
:type costs: List[int]
:rtype: int
"""
dp = [0 for _ in range(days[-1] + 1)]
days_index = 0
for i in range(1,len(dp)):
if i != days[days_index]:
dp[i] = dp[i-1]
else:
dp[i] = min(dp[max(0,i-1)] + costs[0]
,dp[max(0,i-7)] + costs[1]
,dp[max(0,i-30)] + costs[2])
days_index += 1
return dp[-1]
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1 = sorted(nums1)
nums2 = sorted(nums2)
l1 = 0
l2 = 0
res = []
while l1 < len(nums1) and l2 < len(nums2):
if nums1[l1] < nums2[l2]: l1 += 1
elif nums1[l1] > nums2[l2]: l2 += 1
else:
res.append(nums1[l1])
l1 += 1
l2 += 1
return res
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1 = sorted(nums1)
nums2 = sorted(nums2)
l1 = 0
l2 = 0
res = []
while l1 < len(nums1) and l2 < len(nums2):
if nums1[l1] < nums2[l2]: l1 += 1
elif nums1[l1] > nums2[l2]: l2 += 1
else:
res.append(nums1[l1])
l1 += 1
l2 += 1
return res
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
left = 0
right = len(height) - 1
max_area = 0
while left < right:
max_area = max(max_area,min(height[left],height[right]) * (right - left))
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_area
class Solution(object):
def longestRepeatingSubstring(self, s):
"""
:type s: str
:rtype: int
"""
max_sub_length = 0
dp = [[0 for _ in range(len(s))] for _ in range(len(s))]
for i in range(len(s)):
for j in range(len(s)):
if i == 0 or j == 0:
if s[i] == s[j] and i != j:
dp[i][j] = 1
else:
dp[i][j] = 0
else:
if s[i] == s[j] and i != j:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = 0
max_sub_length = max(max_sub_length,dp[i][j])
return max_sub_length
class Solution(object):
def findLength(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
res = 0
dp = [[0 for _ in range(len(nums2))] for _ in range(len(nums1))]
for i in range(len(nums1)):
for j in range(len(nums2)):
if i == 0 or j == 0:
if nums1[i] == nums2[j]:
dp[i][j] = 1
else:
dp[i][j] = 0
else:
if nums1[i] == nums2[j]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = 0
res = max(res,dp[i][j])
return res
class Solution(object):
def massage(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0: return 0
if len(nums) == 1: return nums[0]
if len(nums) == 2: return max(nums[0],nums[1])
dp = [0 for _ in range(len(nums))]
dp[0] = nums[0]
dp[1] = max(nums[0],nums[1])
dp[2] = max(nums[1],nums[0] + nums[2])
for i in range(3,len(nums)):
dp[i] = max(dp[i-2] + nums[i],dp[i-1])
return dp[-1]
class Solution(object):
def trap(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0: return 0
max_value = 0
max_index = nums.index(max(nums))
left = 0
for i in range(left,max_index+1):
if nums[left] > nums[i]:
max_value += (nums[left] - nums[i])
else:
left = i
right = len(nums) - 1
for j in range(right,max_index-1,-1):
if nums[right] > nums[j]:
max_value += (nums[right] - nums[j])
else:
right = j
return max_value
class Solution(object):
def findRepeatedDnaSequences(self, s):
"""
:type s: str
:rtype: List[str]
"""
i = 0
j = 9
dict = {}
res = set()
while j < len(s):
sub_string = s[i:j+1]
if sub_string not in dict:
dict[sub_string] = 1
else:
res.add(sub_string)
i += 1
j += 1
return list(res)
class Solution(object):
def findMinArrowShots(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
points = sorted(points,key=lambda x : x[0])
arrow_cnt = 1
curr_right = points[0][1]
for i in range(1,len(points)):
next_left = points[i][0]
next_right = points[i][1]
if next_left <= curr_right:
if next_right < curr_right:
curr_right = next_right
else:
curr_right = points[i][1]
arrow_cnt += 1
return arrow_cnt
class Solution(object):
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
intervals = sorted(intervals,key=lambda x: x[0])
cancle_cnt = 0
curr_right = intervals[0][1]
for i in range(1,len(intervals)):
next_left = intervals[i][0]
if curr_right > next_left:
if curr_right > intervals[i][1]:
curr_right = intervals[i][1]
cancle_cnt += 1
else:
curr_right = intervals[i][1]
return cancle_cnt
class Solution(object):
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
len_s1 = len(s1)
i = 0
j = i + len_s1 - 1
def cnt_s(s1):
dict_s1 = {}
for i in range(len(s1)):
if s1[i] not in dict_s1:
dict_s1[s1[i]] = 1
else:
dict_s1[s1[i]] += 1
return dict_s1
dict_s1 = cnt_s(s1)
while j < len(s2):
temp = s2[i:j+1]
dict_s2 = cnt_s(temp)
if dict_s1 == dict_s2:
return True
i += 1
j += 1
return False
class Solution:
def permutation(self, s: str) -> List[str]:
c, res = list(s), []
def dfs(x):
if x == len(c) - 1:
res.append(''.join(c))
return
dic = set()
for i in range(x, len(c)):
if c[i] in dic: continue
dic.add(c[i])
c[i], c[x] = c[x], c[i]
dfs(x + 1)
c[i], c[x] = c[x], c[i]
dfs(0)
return res
class Solution(object):
def permutation(self, s):
"""
:type s: str
:rtype: List[str]
"""
res = []
s = list(s)
def dfs(x):
if x == len(s):
res.append(''.join(s))
return
dictt = {}
for i in range(x,len(s)):
if s[i] in dictt:
continue
else:
dictt[s[i]] = 1
s[x],s[i] = s[i],s[x]
dfs(x+1)
s[i],s[x] = s[x],s[i]
dfs(0)
return res
class Solution:
def permute(self, nums) :
c, res = nums, []
def dfs(x):
if x == len(c):
tmp = [ci for ci in c]
res.append(tmp)
return
dic = set()
for i in range(x, len(c)):
if c[i] in dic: continue
dic.add(c[i])
c[i], c[x] = c[x], c[i]
dfs(x + 1)
c[i], c[x] = c[x], c[i]
dfs(0)
return res
class Solution:
def calculateMinimumHP(self, dungeon):
n, m = len(dungeon), len(dungeon[0])
BIG = 10**9
dp = [[BIG] * (m + 1) for _ in range(n + 1)]
dp[n][m - 1] = dp[n - 1][m] = 1
for i in range(n - 1, -1, -1):
for j in range(m - 1, -1, -1):
minn = min(dp[i + 1][j], dp[i][j + 1])
dp[i][j] = max(minn - dungeon[i][j], 1)
return dp[0][0]
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m = len(grid)
n = len(grid[0])
dp = [[10**9]*(n+1) for j in range(m+1)]
dp[m][n-1] = 0
dp[m-1][n] = 0
for i in range(m-1,-1,-1):
for j in range(n-1,-1,-1):
dp[i][j] = min(dp[i+1][j],dp[i][j+1]) + grid[i][j]
return dp[0][0]
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 or j == 0:
dp[i][j] = 1
else:
dp[i][j] = dp[i-1][j]+ dp[i][j-1]
return dp[-1][-1]
class Solution(object):
def makesquare(self, matchsticks):
"""
:type matchsticks: List[int]
:rtype: bool
"""
matchsticks = sorted(matchsticks,reverse=True)
if sum(matchsticks) % 4 != 0: return False
if len(matchsticks) < 4 : return False
buckets = [0] *4
edge = sum(matchsticks) // 4
def dfs(x):
if x == len(matchsticks):
return True
for i in range(len(buckets)):
if matchsticks[x] + buckets[i] > edge:
continue
buckets[i] += matchsticks[x]
if dfs(x+1): return True
buckets[i] -= matchsticks[x]
return False
return dfs(0)
class Solution(object):
def characterReplacement(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
word_cnt = {}
max_len = 0
left = 0
right = 0
while right < len(s):
if s[right] not in word_cnt:
word_cnt[s[right]] = 1
else:
word_cnt[s[right]] += 1
if max(word_cnt.values()) + k < right - left + 1:
word_cnt[s[left]] -= 1
left += 1
max_len = max(max_len,right-left+1)
right += 1
return max_len
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1: return nums[0]
if len(nums) == 2: return max(nums[0],nums[1])
dp = [0] * len(nums)
dp[0] = nums[0]
dp[1] = max(nums[0],nums[1])
for i in range(2,len(nums)):
dp[i] = max(dp[i-1] , dp[i-2] + nums[i])
return dp[-1]
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
node1,node2 = headA,headB
while headA!=headB:
if headA:
headA = headA.next
else:
headA = node2
if headB:
headB = headB.next
else:
headB = node1
return headA
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums) == 0 : return 0
index = self.binary_search(nums,target)
if index == 'not exists': return 0
left = index
right = index
while left > 0 and nums[left-1] == nums[index]: left -= 1
while right < len(nums) - 1 and nums[right+1] == nums[index]: right += 1
return right - left + 1
def binary_search(self,nums,target):
left = 0
right = len(nums) - 1
while left <= right:
mid = left + (right-left)//2
if nums[mid] > target:
right = mid - 1
elif nums[mid] < target:
left = mid + 1
else:
return mid
return 'not exists'
class Solution(object):
def getLeastNumbers(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: List[int]
"""
def quick_sort(arr,left,right):
pivot = left
i,j = left,right
if i >= j : return
while i < j :
while i < j and arr[j] >= arr[pivot]: j -= 1
while i < j and arr[i] <= arr[pivot]: i += 1
arr[i],arr[j] = arr[j],arr[i]
arr[pivot],arr[i] = arr[i],arr[pivot]
quick_sort(arr,left,i-1)
quick_sort(arr,i+1,right)
return arr
left = 0
right = len(arr) - 1
return quick_sort(arr,left,right)[:k]
class Solution(object):
def getLeastNumbers(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: List[int]
"""
def quick_sort(left,right,arr):
pivot = left
i = left
j = right
if i >= j : return
while i < j:
while i < j and arr[j] >= arr[pivot]: j -= 1
while i < j and arr[i] <= arr[pivot] : i += 1
arr[i],arr[j] = arr[j],arr[i]
arr[pivot],arr[i] = arr[i],arr[pivot]
quick_sort(left,i-1,arr)
quick_sort(i+1,right,arr)
return arr
left = 0
right = len(arr) - 1
return quick_sort(left,right,arr)[:k]
那就是记录每个丑数是否已经被乘2, 乘3, 乘5了,
具体的做法是设置3个索引a, b, c,分别记录前几个数已经被乘2, 乘3, 乘5了
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0] * n
dp[0] = 1
index1,index2,index3 = 0,0,0
for i in range(1,n):
temp_index1 = dp[index1] * 2
temp_index2 = dp[index2] * 3
temp_index3 = dp[index3] *5
dp[i] = min(dp[index1]*2,dp[index2]*3,dp[index3]*5)
if temp_index1 == dp[i]: index1 += 1
if temp_index2 == dp[i]: index2 += 1
if temp_index3 == dp[i]: index3 += 1
return dp[-1]
class Solution(object):
def isUgly(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 0 : return False
while n % 2 == 0:
n /= 2
while n % 3 == 0:
n /= 3
while n % 5 == 0:
n/= 5
return n == 1
class Solution(object):
def nthSuperUglyNumber(self, n,primes):
"""
:type n: int
:rtype: int
"""
dp = [0] * n
dp[0] = 1
m = len(primes)
indexs = [0] * m
for i in range(1,n):
dp[i] = min(dp[indexs[j]]*primes[j] for j in range(m))
for j in range(m):
if dp[indexs[j]] *primes[j] == dp[i]:
indexs[j] += 1
return dp[-1]
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: str
"""
dict = {}
for i in range(len(s)):
if s[i] not in dict:
dict[s[i]] = 1
else:
dict[s[i]] += 1
for i in range(len(s)):
if dict[s[i]] == 1:
return s[i]
return " "
class Solution(object):
def minNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
for j in range(len(nums)):
for i in range(len(nums) - 1, j, -1):
if str(nums[i-1]) + str(nums[i]) > str(nums[i]) + str(nums[i-1]):
nums[i],nums[i-1] = nums[i-1],nums[i]
return ''.join([str(num) for num in nums])
class Solution(object):
def divingBoard(self, shorter, longer, k):
"""
:type shorter: int
:type longer: int
:type k: int
:rtype: List[int]
"""
if k == 0 : return []
if shorter == longer: return [shorter * k]
res = []
for i in range(k,-1,-1):
temp = shorter*i + longer* (k-i)
res.append(temp)
return res
class Solution(object):
def cuttingRope(self, n):
"""
:type n: int
:rtype: int
"""
if n <=2 : return 1
if n == 3 : return 2
dp = [0] * (n+1)
dp[1] = 1
dp[2] = 2
dp[3] = 3
for i in range(4,n+1):
for j in range(i//2+1):
dp[i] = max(dp[i],dp[j] * dp[i-j])
return dp[-1]
class Solution(object):
def cuttingRope(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 2: return 1
if n == 3: return 2
dp = [0] * (n + 1)
dp[1] = 1
dp[2] = 2
dp[3] = 3
for i in range(4,n+1):
for j in range(1,i//2+1):
dp[i] = max(dp[i],dp[j] * dp[i-j])
return dp[-1]
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
hashh = {}
max_len = 0
for num in nums:
if num not in hashh:
hashh[num] = 1
else:
hashh[num] += 1
for num in set(nums):
left = num
right = num
if not hashh.__contains__(right-1):
while hashh.__contains__(right+1):
right = right + 1
max_len = max(max_len,right - left + 1)
return max_len
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0: return 0
nums = list(sorted(set(nums)))
left = 0
right = 1
max_window = 1
while right < len(nums):
if nums[right] - nums[left] + 1 == right - left + 1:
max_window = max(max_window,right - left+1)
right += 1
else:
left = right
return max_window
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums = sorted(nums)
res = []
for i in range(len(nums)):
if(i>0 and nums[i]==nums[i-1]):
continue
target = 0 - nums[i]
left = i + 1
right = len(nums) - 1
while left < right:
if nums[left] + nums[right] > target:
right = right - 1
elif nums[left] + nums[right] < target:
left = left +1
else:
res.append((nums[i],nums[left],nums[right]))
while(left<right and nums[left]==nums[left+1]):
left=left+1
while(left<right and nums[right]==nums[right-1]):
right=right-1
left += 1
right -= 1
return res
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
res = len(s)
for i in range(len(s)):
left,right = i,i
while left > 0 and s[left-1] == s[i]:
left -= 1
res += 1
while left > 0 and right < len(s) - 1 and s[left-1] == s[right+1]:
left -= 1
right += 1
res += 1
return res
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if not digits: return []
M = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
}
current = []
res = []
def dfs(x):
if x == len(digits):
res.append(''.join(current))
return
num = digits[x]
for letter in M[num]:
print('letter: ',letter)
current.append(letter)
dfs(x+1)
current.pop()
dfs(0)
return res
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) < 1: return True
dictt = {')':'(','}':'{',']':'['}
temp = ['?']
for letter in s:
if letter not in dictt:
temp.append(letter)
else:
if temp[-1] == dictt[letter]: temp.pop()
else: return False
return len(temp) == 1
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) < 1: return [-1,-1]
left = 0
right = len(nums) - 1
while left < len(nums) and nums[left] != target:left += 1
while right >= 0 and nums[right] != target: right -= 1
if left == len(nums) : left = -1
if right == -1 : right = -1
return[left,right]
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if not head: return
pre = ListNode(-1)
pre.next = head
dummy = pre
curr = pre
for i in range(n):
curr = curr.next
while curr.next:
dummy = dummy.next
curr = curr.next
dummy.next = dummy.next.next
return pre.next
from typing import 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
"""
dummy = ListNode(-1)
curr = dummy
while l1 and l2 :
if l1.val <= l2.val:
curr.next = l1
l1 = l1.next
curr = curr.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
if l1:
curr.next = l1
if l2:
curr.next = l2
return dummy.next
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if target >= nums[0]:
if nums[mid] < nums[0]:
nums[mid] = 2**10
else:
if nums[mid] >= nums[0]:
nums[mid] = -2**10
if nums[mid] > target:
right = mid - 1
elif nums[mid] < target:
left = mid + 1
else:
return mid
return -1
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if target >= nums[0]:
if nums[mid] < nums[0]:
nums[mid] = 2**10
else:
if nums[mid] >= nums[0]:
nums[mid] = -2**10
if nums[mid] > target:
right = mid - 1
elif nums[mid] < target:
left = mid + 1
else:
return mid
return -1
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
if len(intervals) < 1: return []
if len(intervals) == 1 : return intervals
intervals = sorted(intervals,key = lambda x : x[0])
res = []
curr_left = intervals[0][0]
curr_right = intervals[0][1]
for i in range(len(intervals)-1):
next_left = intervals[i+1][0]
next_right = intervals[i+1][1]
if curr_right >= next_left:
if curr_right < next_right:
curr_right = next_right
else:
res.append([curr_left,curr_right])
curr_left = next_left
curr_right = next_right
if i == len(intervals) - 2: res.append([curr_left,curr_right])
return res
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
intervals = sorted(intervals,key=lambda b:b[0])
res = []
left = intervals[0][0]
right = intervals[0][1]
for i in range(1,len(intervals)):
if right >= intervals[i][0]:
if right < intervals[i][1]:
right = intervals[i][1]
else:
res.append([left,right])
left = intervals[i][0]
right = intervals[i][1]
res.append([left,right])
return res
class Solution(object):
def __init__(self) -> None:
super().__init__()
self.res = []
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root : return
self.inorderTraversal(root.left)
self.res.append(root.val)
self.inorderTraversal(root.right)
return self.res
class Solution(object):
def findNumberIn2DArray(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
i = len(matrix) - 1
j = 0
while i >= 0 and j < len(matrix[0]):
if matrix[i][j] > target : i -= 1
elif matrix[i][j] <target : j += 1
else: return True
return False
class Solution(object):
def singleNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
dictt = {}
res = []
for num in nums:
if num not in dictt:
dictt[num] = 1
else:
dictt[num] = 0
for keyy in dictt:
if dictt[keyy] == 1:
res.append(keyy)
return res
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = ListNode(-1)
curr = dummy
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
curr = curr.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
if l1:
curr.next = l1
if l2:
curr.next = l2
return dummy.next
class Solution(object):
def isSubStructure(self, A, B):
"""
:type A: TreeNode
:type B: TreeNode
:rtype: bool
"""
if not A or not B : return False
def recur(A,B):
if not B : return True
if not A or A.val != B.val : return False
return recur(A.left,B.left) and recur(A.right,B.right)
return recur(A,B) or self.isSubStructure(A.left,B) or self.isSubStructure(A.right,B)
class Solution(object):
def isSubStructure(self, A, B):
"""
:type A: TreeNode
:type B: TreeNode
:rtype: bool
"""
if not A or not B : return False
def is_Same(A,B):
if not B: return True
if not A or A.val != B.val: return False
return is_Same(A.left,B.left) and is_Same(A.right,B.right)
return is_Same(A,B) or self.isSubStructure(A.left,B) or self.isSubStructure(A.right,B)
class Solution(object):
def mirrorTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root: return
temp = root.left
root.left = self.mirrorTree(root.right)
root.right = self.mirrorTree(temp)
return root
class Solution(object):
def digitsum(self,n):
ans = 0
while n:
ans += n % 10
n //= 10
return ans
def movingCount(self, m, n, k):
vis = set([(0, 0)])
for i in range(m):
for j in range(n):
if ((i - 1, j) in vis or (i, j - 1) in vis) and self.digitsum(i) + self.digitsum(j) <= k:
vis.add((i, j))
return len(vis)
class Solution(object):
def movingCount(self, m, n, k):
"""
:type m: int
:type n: int
:type k: int
:rtype: int
"""
def cal_sum(m,n):
summ = 0
while m :
yu = m % 10
m = m // 10
summ += yu
while n:
yu1 = n % 10
n = n // 10
summ += yu1
return summ
vias = set([(0,0)])
for i in range(m):
for j in range(n):
if ((i-1,j) in vias or (i,j-1) in vias) and cal_sum(i,j) <= k :
vias.add((i,j))
return len(vias)
class Solution:
def exist(self, board, word):
def dfs(i, j, k):
if not 0 <= i < len(board) or not 0 <= j < len(board[0]) or board[i][j] != word[k]: return False
if k == len(word) - 1: return True
board[i][j] = ''
res = dfs(i + 1, j, k + 1) or dfs(i - 1, j, k + 1) or dfs(i, j + 1, k + 1) or dfs(i, j - 1, k + 1)
board[i][j] = word[k]
return res
for i in range(len(board)):
for j in range(len(board[0])):
if dfs(i, j, 0): return True
return False
class Solution(object):
def reversePrint(self, head):
"""
:type head: ListNode
:rtype: List[int]
"""
res = []
p = None
while head:
q = head.next
head.next = p
p = head
head = q
while p:
res.append(p.val)
p = p.next
return res
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
res = []
while matrix:
res += matrix.pop(0)
matrix = list(zip(*matrix))[::-1]
return res
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix: return []
res = []
top = 0
right = len(matrix[0]) - 1
bottom = len(matrix) - 1
left = 0
while top <= bottom and left <= right:
for i in range(left,right+1):
res.append(matrix[top][i])
top += 1
if top > bottom: break
for i in range(top,bottom+1):
res.append(matrix[i][right])
right -= 1
if left > right: break
for i in range(right,left-1,-1):
res.append(matrix[bottom][i])
bottom -= 1
for i in range(bottom,top-1,-1):
res.append(matrix[i][left])
left += 1
return res
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if not preorder: return None
root = TreeNode(preorder[0])
root_index = preorder[0]
inorder_root_index = inorder.index(root_index)
left_tree_inorder = inorder[:inorder_root_index]
right_tree_inorder = inorder[inorder_root_index+1:]
left_tree_preorder = preorder[1:inorder_root_index+1]
right_tree_preorder = preorder[inorder_root_index+1:]
root.left = self.buildTree(left_tree_preorder,left_tree_inorder)
root.right = self.buildTree(right_tree_preorder,right_tree_inorder)
return root
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if x== 0 : return 0
res = 1
if n < 0: x , n = 1/x , -n
while n :
if n & 1: res *= x
x *= x
n >>= 1
return res
class Solution(object):
def deleteNode(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy = ListNode(-1)
curr = dummy
dummy.next = head
while head:
if head.val != val:
head = head.next
curr = curr.next
else:
curr.next = curr.next.next
break
return dummy.next
while True:
try:
NM = [int(i) for i in input().split(' ')]
N = NM[0]
M = NM[1]
scores = []
scores = [int(i) for i in input().split(' ')]
lines = []
for i in range(M):
line = [j for j in input().split(' ')]
lines.append(line)
res = []
for line in lines:
C = line[0]
A = int(line[1])
B = int(line[2])
if C == 'U':
scores[A-1] = B
if C == 'Q':
if A > B:
max_score = max(scores[B-1:A])
elif A < B:
max_score = max(scores[A-1:B])
else:
max_score = scores[A-1]
res.append(max_score)
for ress in res:
print(ress)
except:
break
import heapq
class Solution(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
intervals = sorted(intervals,key=lambda k:k[0])
rooms = []
heapq.heappush(rooms,intervals[0][1])
for i in range(1,len(intervals)):
if rooms[0] < intervals[i][0]:
heapq.heappop(rooms)
heapq.heappush(rooms,intervals[i][1])
return len(rooms)
1002. 查找常用字符
class Solution(object):
def commonChars(self, A):
"""
:type words: List[str]
:rtype: List[str]
"""
res = []
key = set(A[0])
for k in key:
minimum = min(a.count(k) for a in A)
res += minimum*k
return res
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
res = ''
for i in zip(*strs):
if len(set(i)) == 1:
res += i[0]
else:
break
return res
class CQueue(object):
def __init__(self):
self.A = []
self.B = []
def appendTail(self, value):
"""
:type value: int
:rtype: None
"""
self.A.append(value)
def deleteHead(self):
"""
:rtype: int
"""
if self.B : return self.B.pop()
if self.A:
while self.A:
self.B.append(self.A.pop())
return self.B.pop()
return -1
class Solution(object):
def replaceSpace(self, s):
"""
:type s: str
:rtype: str
"""
s = list(s)
i = len(s) - 1
cnt = 0
while i >= 0:
if s[i] == ' ':
cnt += 1
i -= 1
ss = [' '] * (len(s) + 2*cnt)
i = len(ss) - 1
j = len(s) - 1
while j >= 0 :
while j >= 0 and s[j] != ' ':
ss[i] = s[j]
i -= 1
j -= 1
while j >= 0 and s[j] == ' ':
ss[i] = '0'
ss[i-1] = '2'
ss[i-2] = '%'
i = i - 3
j = j - 1
return ''.join(ss)
import collections
from typing import List
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrder(self, root):
res = []
queue = collections.deque()
if not root:
return []
queue.append(root)
while queue:
tmp = []
for _ in range(len(queue)):
root = queue.popleft()
tmp.append(root.val)
if root.left:
queue.append(root.left)
if root.right:
queue.append(root.right)
res.append(tmp)
return res
import collections
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: str
"""
if len(s) < 1: return ' '
hashh = {}
for letter in s:
if letter not in hashh:
hashh[letter] = 1
else:
hashh[letter] += 1
for letter in s:
if hashh[letter] == 1:
return letter
return ' '
class Solution(object):
def firstUniqChar(self, s):
queue = collections.deque()
first = {}
for i,letter in enumerate(s):
if letter not in first:
first[letter] = i
queue.append((letter,i))
else:
first[letter] = -1
while queue and first[queue[0][0]] == -1 :
queue.popleft()
return queue[0][0] if queue else ' '
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(len(s)):
for j in range(i+1,len(s)+1):
if dp[i] and s[i:j] in wordDict:
dp[j] = True
return dp[-1]
class Solution:
def reverseWords(self, s: str) -> str:
s = s.strip()
i = j = len(s) - 1
res = []
while i >= 0:
while i >= 0 and s[i] != ' ': i -= 1
res.append(s[i + 1: j + 1])
while s[i] == ' ': i -= 1
j = i
return ' '.join(res)
class Solution(object):
def flipAndInvertImage(self, image):
"""
:type image: List[List[int]]
:rtype: List[List[int]]
"""
for row in range(len(image)):
image[row] = image[row][::-1]
for row in range(len(image)):
for column in range(len(image[0])):
image[row][column] = 1 - image[row][column]
return image
class Solution(object):
def flipAndInvertImage(self, image):
"""
:type image: List[List[int]]
:rtype: List[List[int]]
"""
for row in range(len(image)):
image[row] = image[row][::-1]
for column in range(len(image[row])):
image[row][column] = 1 - image[row][column]
return image
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) < 1: return -1,-1
left = 0
right = left
while left < len(nums) and nums[left] != target:
left += 1
right = left
while right < len(nums) and nums[right] == target:
right += 1
if left == len(nums): return -1,-1
return left,right
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
left = 0
right = len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] > target:
right = mid - 1
elif nums[mid] < target:
left = mid + 1
else:
left = mid
right = mid
while left > 0 and nums[left-1] == target:
left -= 1
while right < len(nums) - 1 and nums[right+1] == target:
right += 1
return left,right
return -1,-1
m,n = input().split(' ')
m = int(m)
n = int(n)
res = []
for i in range(m):
temp = []
row = input().split(' ')
for j in range(n):
temp.append(int(row[j]))
res.append(temp)
BIG = 10 ** 9
dp = [[BIG] * (n+1) for _ in range(m+1)]
dp[n][m-1] = dp[n-1][m] = 1
for i in range(m-1,-1,-1):
for j in range(n-1,-1,-1):
minn = min(dp[i+1][j],dp[i][j+1])
dp[i][j] = max(minn - res[i][j],1)
print(dp[0][0])
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
up = len(matrix) - 1
right = 0
while up >= 0 and right <= len(matrix[0]) - 1:
if matrix[up][right] > target:
up -= 1
elif matrix[up][right] < target:
right += 1
else:
return True
return False
class Solution(object):
def getLeastNumbers(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: List[int]
"""
def quick_sort(arr,left,right):
if left >= right: return
pivot = left
i,j = left,right
while i < j:
while i < j and arr[j] >= arr[pivot]: j-= 1
while i < j and arr[i] <= arr[pivot]: i += 1
arr[i],arr[j] = arr[j],arr[i]
arr[pivot],arr[i] = arr[i],arr[pivot]
quick_sort(arr,left,i-1)
quick_sort(arr,i+1,right)
return arr
left = 0
right = len(arr) - 1
return quick_sort(arr,left,right)
arr = [3,2,1]
k = 2
solution = Solution()
print(solution.getLeastNumbers(arr,k))
while True:
try:
NM = [i for i in input().split(' ')]
N = int(NM[0])
M = int(NM[1])
scores = [int(i) for i in input().split(' ')]
for row in range(M):
ops = [i for i in input().split(' ')]
opt = ops[0]
A = int(ops[1])
B = int(ops[2])
if opt =='U':
scores[A-1] = B
if opt == 'Q':
if A < B:
print(max(scores[A-1:B]))
elif A > B:
print(max(scores[B-1:A]))
else:
print(scores[A-1])
except:
break
import sys
dct = {}
for line in sys.stdin:
ele = line.split('\\')[-1].strip('\n')
if ele in dct:
dct[ele] += 1
else:
dct[ele] = 1
lst = sorted(dct.items(),key=lambda d: d[1],reverse=True)
count = 0
for key in lst:
if count > 7:
break
count += 1
if len(key[0].split(' ')[0]) > 16 :
print(key[0].split(' ')[0][-16:],key[0].split(' ')[1],key[1])
else:
print(key[0].split(' ')[0],key[0].split(' ')[1],key[1])
def choose_m(n,x,y,ais):
ais = sorted(ais)
left = x
right = y
i = left
while i <= right:
if n - i <= right and n-i >= left and ais[i]!= ais[i-1]:
minn = ais[i-1]
break
i += 1
return minn
def main():
row1 = [int(i) for i in input().split(' ')]
n = row1[0]
x = row1[1]
y = row1[2]
scores = [int(i) for i in input().split(' ')]
print(choose_m(n,x,y,scores))
main()
n = int(input())
nums = [int(i) for i in input().split(' ')]
sum = 0
nums = sorted(nums)
for i in range(1,(n+1)):
sum += abs(nums[i-1] - i)
print(sum)
import heapq
people = [0,1,1,0,2]
M = 6
genders = 'MFMMFF'
heap0 = []
heap1 = []
for i,person in enumerate(people,start=1):
if person == 0:
heapq.heappush(heap0,i)
if person == 1:
heapq.heappush(heap1,i)
for gender in genders:
f1 = heap1[0] if heap1 else 0
f0 = heap0[0] if heap0 else 0
if gender == 'M':
if f1:
print(f1)
heapq.heappop(heap1)
else:
print(f0)
heapq.heappush(heap1,heapq.heappop(heap0))
else:
if f0:
print(f0)
heapq.heappush(heap1,heapq.heappop(heap0))
else:
print(f1)
heapq.heappop(heap1)
import heapq
people = [0,1,1,0,2]
M = 6
genders = 'MFMMFF'
heap0 = []
heap1 = []
for i,person in enumerate(people,start=1):
if person == 0:
heapq.heappush(heap0,i)
if person == 1:
heapq.heappush(heap1,i)
for gender in genders:
f1 = heap1[0] if heap1 else 0
f0 = heap0[0] if heap0 else 0
if gender == 'M':
if f1:
print(f1)
heapq.heappop(heap1)
else:
print(f0)
heapq.heappush(heap1,heapq.heappop(heap0))
else:
if f0:
print(f0)
heapq.heappush(heap1,heapq.heappop(heap0))
else:
print(f1)
heapq.heappop(heap1)
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
res = []
def dfs(root):
if root != None:
dfs(root.left)
res.append(root.val)
dfs(root.right)
dfs(root)
return res[k-1]
class Solution(object):
def twoCitySchedCost(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
costs = sorted(costs,key = lambda x: x[0] - x[1])
n = len(costs) // 2
total = 0
for i in range(n):
total += costs[i][0] + costs[i+n][1]
return total
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
class Solution(object):
def exchange(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
left = 0
right = len(nums) - 1
while left < right:
while left < right and nums[left]%2 != 0: left += 1
while left < right and nums[right] % 2 == 0 : right -= 1
nums[left],nums[right] = nums[right],nums[left]
return nums
class Solution(object):
def getLeastNumbers(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: List[int]
"""
def quick_sort(arr,left,right):
if left >= right: return
pivot = left
i,j = left,right
while i < j:
while i < j and arr[j] >= arr[pivot]: j-= 1
while i < j and arr[i] <= arr[pivot]: i += 1
arr[i],arr[j] = arr[j],arr[i]
arr[pivot],arr[i] = arr[i],arr[pivot]
quick_sort(arr,left,i-1)
quick_sort(arr,i+1,right)
return arr
left = 0
right = len(arr) - 1
return quick_sort(arr,left,right)
arr = [3,2,1]
k = 2
solution = Solution()
print(solution.getLeastNumbers(arr,k))
while True:
try:
NM = [i for i in input().split(' ')]
N = int(NM[0])
M = int(NM[1])
scores = [int(i) for i in input().split(' ')]
for row in range(M):
ops = [i for i in input().split(' ')]
opt = ops[0]
A = int(ops[1])
B = int(ops[2])
if opt =='U':
scores[A-1] = B
if opt == 'Q':
if A < B:
print(max(scores[A-1:B]))
elif A > B:
print(max(scores[B-1:A]))
else:
print(scores[A-1])
except:
break
import sys
dct = {}
for line in sys.stdin:
ele = line.split('\\')[-1].strip('\n')
if ele in dct:
dct[ele] += 1
else:
dct[ele] = 1
lst = sorted(dct.items(),key=lambda d: d[1],reverse=True)
count = 0
for key in lst:
if count > 7:
break
count += 1
if len(key[0].split(' ')[0]) > 16 :
print(key[0].split(' ')[0][-16:],key[0].split(' ')[1],key[1])
else:
print(key[0].split(' ')[0],key[0].split(' ')[1],key[1])
def choose_m(n,x,y,ais):
ais = sorted(ais)
left = x
right = y
i = left
while i <= right:
if n - i <= right and n-i >= left and ais[i]!= ais[i-1]:
minn = ais[i-1]
break
i += 1
return minn
def main():
row1 = [int(i) for i in input().split(' ')]
n = row1[0]
x = row1[1]
y = row1[2]
scores = [int(i) for i in input().split(' ')]
print(choose_m(n,x,y,scores))
main()
n = int(input())
nums = [int(i) for i in input().split(' ')]
sum = 0
nums = sorted(nums)
for i in range(1,(n+1)):
sum += abs(nums[i-1] - i)
print(sum)
import heapq
T = int(input())
while T:
T -= 1
N = int(input())
people = [int(i) for i in input()]
M = int(input())
genders = input()
heap0 = []
heap1 = []
for i,person in enumerate(people,start=1):
if person == 0:
heapq.heappush(heap0,i)
if person == 1:
heapq.heappush(heap1,i)
for gender in genders:
f1 = heap1[0] if heap1 else 0
f0 = heap0[0] if heap0 else 0
if gender == 'M':
if f1:
print(f1)
heapq.heappop(heap1)
else:
print(f0)
heapq.heappush(heap1,heapq.heappop(heap0))
else:
if f0:
print(f0)
heapq.heappush(heap1,heapq.heappop(heap0))
else:
print(f1)
heapq.heappop(heap1)
while True:
try:
s1 = list(map(int,input().split(' ')))
s2 = list(map(int,input().split(' ')))
n,m,a,b = s1
if a > b: a,b = b,a
cake1,cake2 = min(s2),max(s2)
if cake1 < a or cake2 > b: print('No')
if cake1 == a and cake2 == b: print('Yes')
if cake1 == a or cake2 == b:
if n-m >= 1: print('Yes')
else: print('No')
if cake1 < a and cake2 > b:
if n-m>= 2: print('Yes')
else: print('No')
except:
break
s1 = list(map(int, input().split(' ')))
s2 = list(map(int, input().split(' ')))
n,x = s1
scores = sorted(s2,reverse=True)
num = 0
for score in scores:
if score >= scores[x-1] and score != 0:
num += 1
print(num)
T= int(input())
while T:
T -= 1
N = input()
nums = [int(i) for i in input().split(' ')]
maxx = nums[0]
minn = nums[0]
dpmax = nums[0]
dpmin = nums[0]
for i in range(1,len(nums)):
dpmax = max(dpmax+nums[i],nums[i])
maxx = max(maxx,dpmax)
dpmin = min(dpmin+nums[i],nums[i])
minn = min(dpmin,minn)
print(max(maxx,sum(nums)-minn))
N = input()
s = input()
sum = 0
max_sum = 0
for i in range(len(s)):
if s[i] == 'E': sum += 1
if s[i] == 'F': sum -= 1
sum = max(sum,0)
max_sum = max(max_sum,sum)
print(max_sum)
class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
m = len(word1)
n = len(word2)
dp = [[0] * (n+1) for _ in range(m+1)]
for i in range(m+1):
dp[i][0] = i
for j in range(n+1):
dp[0][j] = j
for i in range(1,m+1):
for j in range(1,n+1):
left = dp[i][j-1] + 1
down = dp[i-1][j] + 1
left_down = dp[i-1][j-1]
if word1[i-1] != word2[j-1]:
left_down = left_down + 1
dp[i][j] = min(left,down,left_down)
return dp[m][n]