zoukankan      html  css  js  c++  java
  • 数组_leetcode215

    #coding=utf-8
    # 解题思路:快速排序 20190302 找工作期间
    # 关键点 index = partion(xx) ,index表示的是在整个数组中的位置

    class Solution(object):
    def findKthLargest(self, nums, k):
    """
    :type nums: List[int]
    :type k: int
    :rtype: int
    """

    length = len(nums)

    if not nums or k <= 0 or k > length:
    return

    start = 0
    end = length-1
    self.fastSort(nums,start,end)

    return nums[length-k]

    def fastSort(self,alist,start,end):
    if end <= start:
    return

    base = alist[start]
    index1 , index2 = start,end

    while start < end :

    while start < end and alist[end] >= base:
    end -= 1
    alist[start] = alist[end]

    while start < end and alist[start] <= base:
    start += 1
    alist[end] = alist[start]

    alist[start] = base

    self.fastSort(alist,index1,start-1)
    self.fastSort(alist,start+1,index2)



    class Solution2(object):
    def findKthLargest(self, nums, k):
    """
    :type nums: List[int]
    :type k: int
    :rtype: int
    """

    length = len(nums)

    if not nums or k <= 0 or k > length:
    return

    start = 0
    end = length-1
    target = length-k

    index = self.partition(nums,start,end)

    while index != target:
    if index > target:
    index = self.partition(nums,start,index-1)
    else:
    index = self.partition(nums,index+1,end)

    return nums[target]

    def partition(self,alist,start,end):

    if end <= start:
    return start

    base = alist[start]
    index1 , index2 = start , end

    while start < end :
    while start < end and alist[end] >= base :
    end -= 1
    alist[start] = alist[end]

    while start < end and alist[start] <= base:
    start += 1
    alist[end] = alist[start]

    alist[start] = base
    return start



    nums1 = [3,2,1,5,6,4]
    k1 = 2

    nums2 = [3,2,3,1,2,4,5,5,6]
    k2 = 4


    s = Solution2()

    print s.findKthLargest(nums2,k2)
  • 相关阅读:
    python 01
    Node.js 基础库
    Node 编程规范
    Linux_异常_08_本机无法访问虚拟机web等工程
    inux_异常_07_ftp查看不到文件列表
    Linux_异常_04_ftp: command not found...
    Linux_异常_03_Failed to restart iptables.service: Unit not found.
    Linux_异常_02_WinSCP上传文件时显示Permission denied
    Linux_异常_01_CentOS7无法ping 百度
    Linux_配置_02_配置dns
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546878.html
Copyright © 2011-2022 走看看