li = [1,2,1,3,2,1,1,2,2,3,3] num = 0 for i in li: num = num ^ i #这里运用了一个异或符号的小技巧 当然只能在数列中只存在唯一一个数字才可使用 print(num)
(2) 快速排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defquick_sort(li, left, right): if left < right: mid = partition(li, left, right) quick_sort(li, left, mid - 1) quick_sort(li, mid + 1, right) defpartition(li, left, right): tmp = li[left] while left < right: while left < right and li[right] >= tmp: right -= 1 li[left] = li[right] while left < right and li[left] <= tmp: left += 1 li[right] = li[left] li[left] = tmp return left
defquick_sort(li, left, right): if left < right: mid = random_partition(li, left, right) quick_sort(li, left, mid - 1) quick_sort(li, mid + 1, right) defpartition(li, left, right): tmp = li[left] while left < right: while left < right and li[right] >= tmp: right -= 1 li[left] = li[right] while left < right and li[left] <= tmp: left += 1 li[right] = li[left] li[left] = tmp return left defrandom_partition(li, left, right): i = random.randint(left, right) li[i], li[left] = li[left], li[i] partition(li, left, right)
(3) 快速排序 切片实现
1 2 3 4 5 6 7 8 9
defquick_sort(li): if len(li) < 2: return li tmp = li[0] left = [i for i in li[1:] if i <= tmp] right = [i for i in li[1:] if i > tmp] left = quick_sort(left) right = quick_sort(right) return left + [tmp] + right
classSolution(object): defsortArray(self, nums): """ :type nums: List[int] :rtype: List[int] """ #return self.quick_sort(nums, 0, len(nums) - 1) return self.quick_sort(nums) ''' def quick_sort(self, nums, left, right): if left > right: return if left < right: mid = self.partition(nums, left, right) self.quick_sort(nums, left, mid-1) self.quick_sort(nums, mid+1, right) return nums def partition(self, nums, left, right): tmp = nums[left] while left < right: while left < right and nums[right] >= tmp: right -= 1 nums[left] = nums[right] while left < right and nums[left] <= tmp: left += 1 nums[right] = nums[left] nums[left] = tmp return left ''' defquick_sort(self, nums): if len(nums) < 2: return nums tmp = nums[0] left = [i for i in nums[1:] if i <= tmp] right = [i for i in nums[1:] if i > tmp] left = self.quick_sort(left) right = self.quick_sort(right) return left + [tmp] + right