Fork me on GitHub

【python刷题】快速排序相关

借鉴快速排序的思想

快速排序代码

def quicksort(nums):
    l = 0
    r = len(nums)-1
    _quicksort(nums, l, r)


def _quicksort(nums, left, right):
    l = left
    r = right
    if l < r:
        tmp = nums[l]
        while l < r:
            while l < r and tmp <= nums[r]:
                r -= 1
            nums[l], nums[r] = nums[r], nums[l]
            while l < r and tmp > nums[l]:
                l += 1
            nums[l], nums[r] = nums[r], nums[l]
        _quicksort(nums, left, l)
        _quicksort(nums, l+1, right)
nums = [6,2,4,1,2,3,5,2,7]
quicksort(nums)
print(nums)

借鉴快速排序思想

def findKthLargest(numbers, start, end, k):
  if k < 0 or numbers == [] or start < 0 or end >= len(numbers) or k > end:
    return None
  low = start
  high = end
  key = numbers[start]
  while low < high:
    while low < high and numbers[high] >= key:
      high -= 1
    numbers[low] = numbers[high]
    while low < high and numbers[low] <= key:
      low += 1
    numbers[high] = numbers[low]
  numbers[low] = key
  if low < k:
    return findKthLargest(numbers, low+ 1, end, k)
  elif low > k:
    return findKthLargest(numbers, start, low- 1, k)
  else:
    return numbers[low-1]
numbers = [3,5,6,7,2,-1,9,3]
print(sorted(numbers))
print(findKthLargest(numbers, 0, len(numbers) - 1, 5))

把数组排成最小的数

import functools
def compare(s1, s2):
    if s1+s2 < s2+s1:
        return -1
    elif s1+s2 == s2+s1:
        return 0
    else:
        return 1

class Solution(object):
    def minNumber(self, numbers):
        if not numbers: return ''
        if len(numbers) == 1: return str(numbers[0])
        str_numbers = [str(n) for n in numbers]
        return ''.join(sorted(str_numbers, key=functools.cmp_to_key(compare)))

s  = Solution()
print(s.minNumber([3,30,34,5,9]))
posted @ 2021-02-04 19:08  西西嘛呦  阅读(187)  评论(0编辑  收藏  举报