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

来源:互联网 发布:hlsl 算法 编辑:程序博客网 时间:2024/05/15 16:11

最近在学Python,从基础的语法学起,但是代码这玩意,还是动手为佳,就从实现几个简单的算法开始吧。
题目主要是从leetcode上面找,这题Majority Element想accepted是很容易的,比如直接sort,然后取第K大。我这里利用快排的思想,算法过程不难,就是实现起来中间有些小细节需要注意。快排本身的时间复杂度为O(NlogN),这里主要是不需要对切割的两个序列都进行排列,每次只排列一个序列就可,所以平均的时间复杂度可以达到O(N)。
先贴题:

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.

下面是代码:

class Solution:    # @param num, a list of integers    # @return an integer    def majorityElement(self, num):        return self.select(num, 0, len(num)-1, len(num)/2)    def partition(self, num, l, r):        pivot = num[l]        i = l        j = r        while i < j:            while pivot < num[j] and i < j:                j -= 1            if i < j:                num[i] = num[j]                i += 1            while pivot > num[i] and i < j:                i += 1            if i < j:                num[j] = num[i]                j -= 1        num[i] = pivot        return i    def select(self,num,l,r,k):        if l == r:            return num[l]        i = self.partition(num,l,r)        j = i - l        if j == k:            return num[i]   #分割完后,如果pivot刚刚好就是第K大,直接返回,否则还有两种情况:        if(j < k):            return self.select(num, i+1, r, k-j-1)        else:            return self.select(num,l,i-1,k)
0 0
原创粉丝点击