二分法合并K个有序数组
# 二分合并k个有序数组 nums1 = [2,3,18,23,118,283] nums2 = [4,7,8,19,26,77,1262] nums3 = [1,19,29,33,67,88] nums4 = [36,47,55,88,128,765] data = [nums1, nums2, nums3, nums4] def mergeKnums(nums): n = len(nums) return binarySelect(nums, 0, n-1) def merge2nums(nums1, nums2): if not nums1: return nums2 if not nums2: return nums1 i, j = 0, 0 result = [] while i < len(nums1) and j < len(nums2): if nums1[i] < nums2[j]: result.append(nums1[i]) i += 1 else: result.append(nums2[j]) j += 1 return result def binarySelect(nums, left, right): if left == right: return nums[left] mid = left + (right-left)//2 print(left, mid, right) nums1, nums2 = binarySelect(nums, left, mid), binarySelect(nums, mid+1, right) return merge2nums(nums1, nums2) merge2nums(nums1, nums2) mergeKnums(data)
时刻记着自己要成为什么样的人!