字符串
https://leetcode.com/problems/longest-palindrome/description/
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
flag=0
max_length=0
char_map={}
n=len(s)
for i in s:
if i in char_map:
char_map[i]+=1
else:
char_map[i]=1
for i in char_map.keys():
if char_map[i]%2==0:
max_length+=char_map[i]
else:
max_length+=char_map[i]-1
flag=1
return max_length+flag
数组和矩阵
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
left,right=matrix[0][0],matrix[-1][-1]
while left<right:
mid=(left+right)/2
if sum(bisect.bisect(row,mid) for row in matrix)<k:
left=mid+1
else:
right=mid
return left
位运算
https://leetcode.com/problems/single-number-iii/description/
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
tmp=0
for i in nums:
tmp^=i
j=0
while tmp&1==0:
tmp>>=1
j+=1
tmp=1<<j
first,second=0,0
for num in nums:
if num&tmp:
first^=num
else:
second^=num
return [first,second]
数学进制转换
https://leetcode.com/problems/base-7/description/
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num<0:
return '-'+self.convertToBase7(abs(num))
elif num <7:
return str(num)
else:
return self.convertToBase7(num//7)+str(num%7)
相遇问题
https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/description/
class Solution(object):
def minMoves2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
n=len(nums)
mid=(n-1)//2
count=0
for i in range(n):
count+=abs(nums[i]-nums[mid])
return count
多数投票问题
https://leetcode.com/problems/majority-element/description/
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic={}
for num in nums:
if num not in dic:
dic[num]=1
if dic[num]>len(nums)//2:
return num
else:
dic[num]+=1