Leetcode刷题笔记-sort

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sengo_GWU/article/details/82621335

179. Largest Number

class Solution(object):
    def largestNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        nums = [str(x) for x in nums]
        nums = sorted(nums, cmp=lambda a, b: cmp(a+b, b+a), reverse=True)
        return "".join(nums).lstrip('0') or '0'

324. Wiggle Sort II

nlogn:

class Solution(object):
    def wiggleSort(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        nums.sort()
        half = len(nums[::2])
        nums[::2], nums[1::2] = nums[:half][::-1], nums[half:][::-1]

 O(n)的很难理解,先复制下别人的答案,回头再来研究:

思路:https://leetcode.com/problems/wiggle-sort-ii/discuss/77677/O(n)+O(1)-after-median-Virtual-Indexing

参考:O(N)的时间寻找第K大数——Python

参考:3-partition

class Solution(object):
    def wiggleSort(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        if len(nums) == 1:
            return
        n = len(nums)

        # Index-rewiring.
        f = lambda i:(1+2*(i)) % (n|1)
        
        mid = self.quickselect(0, len(nums) - 1, nums, len(nums) / 2)
        
        # 3 way partition
        i, j, k = 0, 0, n-1

        while j <= k:
            if (nums[f(j)] > mid):
                nums[f(i)], nums[f(j)] = nums[f(j)], nums[f(i)]
                i += 1
                j += 1
            elif nums[f(j)] < mid:
                nums[f(j)], nums[f(k)] = nums[f(k)], nums[f(j)]
                k -= 1
            else:
                j += 1

        print nums

    def quickselect(self, start, end, A, k):
        if start == end:
            return A[start]
            
        mid = self.partition(start, end, A)
        
        if mid == k:
            return A[k]
        elif mid > k:
            return self.quickselect(start, mid - 1, A, k)
        else:
            return self.quickselect(mid + 1, end, A, k)
        
    def partition(self, start, end, A):
        pivotIndex = random.randrange(start, end + 1)
        pivot = A[pivotIndex]
        A[end], A[pivotIndex] = A[pivotIndex], A[end]
        mid = start
        for i in xrange(start, end):
            if A[i] >= pivot:
                A[mid], A[i] = A[i], A[mid]
                mid += 1
        A[mid], A[end] = A[end], A[mid]
        return mid


 

猜你喜欢

转载自blog.csdn.net/Sengo_GWU/article/details/82621335