169. Majority Element
来源:互联网 发布:微信矩阵 编辑:程序博客网 时间:2024/06/11 06:32
题意: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.
思路:其实方法有很多,直接sort求第n/2位的数也可以,但是时间复杂度比较高,可以用字典当做hash table:
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ d = {} for i in nums: if i not in d.keys(): d[i] = 1 else: d[i] += 1 if d[i] > len(nums)/2: return i
或者用个投票的方法:
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ cnt = 0 for i in nums: if not cnt: major = i cnt = 1 elif i != major: cnt -= 1 else: cnt += 1 return major
0 0
- 169.Majority Element && 229. Majority Element II
- [LeetCode]169.Majority Element
- LeetCode 169.Majority Element
- 【LeetCode】169.Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- 169.Majority Element
- [leetcode] 169.Majority Element
- 169. Majority Element
- Leetcode 169. Majority Element
- 【LeetCode】169. Majority Element
- [LeetCode]169. Majority Element
- 169. Majority Element LeetCode
- 169. Majority Element
- 169. Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- Leetcode 169. Majority Element
- Jquery层级选择过滤器
- 迁移学习( Transfer Learning )
- 谈谈互联网后端基础设施
- oracle dblink创建
- VS 连接ORACLE 11g的方法
- 169. Majority Element
- intellij idea中local.properties的写法有点忘了
- 如何hack一个已经发布的Ubuntu Core应用
- Hadoop集群mini安装
- leetcode oj java Gray Code
- poll,ppoll
- React Native 入门课程(1)了解ReactNative
- Android蓝牙开发的一些经验
- jQuery基本过滤选择器