最近在学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
de