打擂台
nums1 = [1, 2, 4, 6, 8] nums2 = [3, 5, 7, 10, 12, 15, 23] # res = [] # while nums1 and nums2: # if nums1[0] < nums2[0]: # res.append(nums1.pop(0)) # else: # res.append(nums2.pop(0)) left, right = 0, 0 res = [] while left < len(nums1) and right < len(nums2): if nums1[left] < nums2[right]: res.append(nums1[left]) left += 1 else: res.append(nums2[right]) right += 1 temp = nums1[left:] + nums2[right:] res += temp print(res)
def test(nums): if not nums: return def helper(nums, start, end): if start >= end: return left, right = start, end mid = (left + right) // 2 piovt = nums[mid] while left < right: if left < right and nums[left] < piovt: left += 1 if left < right and nums[right] > piovt: right -= 1 if left < right: nums[left], nums[right] = nums[right], nums[left] helper(nums, start, mid-1) helper(nums, mid+1, end) return nums return helper(nums, 0, len(nums)-1) nums = [1,20,6,5,7,3] test(nums) nums
def test(nums, target): if not nums: return left, right = 0, len(nums) - 1 # 要小于等于,里面去折半 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid elif nums[mid] < target: left = mid + 1 else: right = mid - 1 return def rotate_search(nums, target): if not nums: return left, right = 0, len(nums)-1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid if nums[mid] > nums[left]: # 左侧有序,右侧循环 if nums[left] < target and nums[mid] > target: right = mid -1 else: left = mid + 1 else: # 左侧循环,右侧有序 if nums[right] > target and nums[mid] < target: left = mid + 1 else: right = mid - 1 return res = test([1,2,3,4,5,6,7], 3) nums = [4,5,6,7,1,2,3] rotate_search(nums, 2)
时刻记着自己要成为什么样的人!