【python刷题】快速排序相关
快速排序代码
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 functoolsdef 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]))
以上是 【python刷题】快速排序相关 的全部内容, 来源链接: utcz.com/z/387395.html