一、重排列
方法一:
class Solution: def isAnagram(self,s,t): """ :param s: str :param t: str :return: bool """ dict1 = {} #{'a':1,'b':2} dict2 = {} for ch in s: dict1[ch] = dict1.get(ch,0) + 1 for ch in t: dict2[ch] = dict2.get(ch,0) + 1 return dict1 == dict2
方法二:
class Solution: def isAnagram(self, s, t): """ :param s: str :param t: str :return: bool """ return sorted(list(s)) == sorted(list(t))
二、二维二分查找
方法一:
class Solution: def searchMatrix(self, matrix, target): """ :param matrix: List[List[int]] :param target: int :return: bool """ #[[],[],[]] m = len(matrix) # 行数 if m == 0: return False n = len(matrix[0]) #列数 if n == 0: return False low = 0 high = m * n - 1 while low <= high: mid =(low + high) // 2 x,y = divmod(mid,n) if matrix[x][y] > target: high = mid - 1 elif matrix[x][y] < target: low = mid + 1 else: return True else: return False
方法二:
class Solution: def searchMatrix(self, matrix, target): if not matrix or target is None: return False rows,cols = len(matrix), len(matrix[0]) low, high = 0,rows * cols - 1 while low <= high: mid = (low + high) / 2 num = matrix[mid / cols][mid % cols] if num == target: return True elif num < target: low = mid + 1 else: high = mid + 1 return False
三、 Two Sum
1、题目描述
2、方法一
class Solution: def binary_search(self,li,left,right,val): while left <= right: #候选区有值 mid = (left + right) // 2 if li[mid][0] == val: return mid elif li[mid][0] > val: #待查找的值在mid左侧 right = mid - 1 else: #li[mid]< val 待查找的值在mid右侧 left = mid + 1 else: return None def twoSum(self,nums,trarget): """ :param self: :param nums: List[int] :param trarget: int :return: """ new_nums = [[num,i] for i,num in enumerate(nums)] new_nums.sort(key = lambda x:x[0]) for i in range(len(new_nums)): a = new_nums[i][0] b = trarget - a if b >= a: #print(b,i+1,len(nums)-1) j = self.binary_search(new_nums,i+1,len(nums)-1,b) else: j = self.binary_search(new_nums, 0, i - 1, b) if j: return sorted([new_nums[i][1],new_nums[j][1]])
3、方法二
def twoSum(self,nums,trarget): """ :param self: :param nums: List[int] :param trarget: int :return: List[int] """ #[1,4,6,7,9,3], 9 #{1:0,4:1,6:2,7:3,9:4} d = {} for i in range(len(nums)): a = nums[i] b = trarget - a if b in d: return [d[b],i] else: d[a] = i
https://leetcode.com/problems/two-sum/description/
四、区域查询
方法一:
def find_a(nums,target): low = 0 high = len(nums) - 1 while low <= high: mid = (low + high) // 2 if target <= nums[mid]: high = mid - 1 else: low = mid + 1 #[1,2,3,2,4,8,10] if low < len(nums): return low else: return -1 def find_b(nums,target): low = 0 high = len(nums) - 1 while low <= high: mid = (low + high) // 2 if target < nums[mid]: high = mid - 1 else: low = mid + 1 if low < len(nums): return low else: return -1