Majority Element
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. [#169]
Examples: Input: [3,2,3] Output: 3 Input: [2,2,1,1,1,2,2] Output: 2
题意:找出数组中出现次数大于数组长度一半的元素
>>> n=[3,2,3] >>> [i for i in n if n.count(i)>len(n)//2][0] 3 >>> n=[2,2,1,1,1,2,2] >>> [i for i in n if n.count(i)>len(n)//2][0] 2
Majority Element II
Given an integer array of size n, find all elements that appear more than [n/3] times.
Note: The algorithm should run in linear time and in O(1) space.
Examples: Input: [3,2,3] Output: [3] Input: [1,1,1,3,3,2,2,2] Output: [1,2]
题意:找出数组中出现次数大于数组长度三分之一的元素
>>> n=[3,2,3] >>> list({i for i in n if n.count(i)>len(n)//3}) [3] >>> n=[1,1,1,3,3,2,2,2] >>> list({i for i in n if n.count(i)>len(n)//3}) [1, 2] >>>