O(N)的时间寻找第K大数——Python
2015-02-06 15:33
344 查看
最近在学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.
下面是代码:
题目主要是从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)
相关文章推荐
- o(n)时间寻找第k小的数
- 强大的随机算法-简洁的O(n)时间复杂度解决查找第k大数问题优化算法
- Algorithm backup ---- Find the kth largest number(寻找第K大数)
- java线性时间寻找第k小元素
- 寻找数组中第K大数
- [LintCode] Median(期望时间复杂度O(n)求中位数和第k大数)
- 线性时间寻找一列无序数中第k大的数
- 如何用O(n)时间复杂度查找第k大数的优化算法 C++程序
- 在数组A中寻找第k小的元素-最坏情况为线性时间的算法
- 寻找数组中第k小的数:平均情况下时间复杂度为O(n)的快速选择算法
- 寻找数组第二大数和第K大数
- Poj 2388 Who's in the Middle 寻找第k大数
- 线性时间复杂度求数组中第K大数
- 寻找第k大数(快排思想)
- 【算法】寻找数组第K大数算法总结
- 分治算法--寻找第k大数
- Python格式化日期时间
- python天天进步(4)--计算时间差
- python中的时间操作
- Python 格式化输出时间字符串函数 strftime