我是靠谱客的博主 多情中心,这篇文章主要介绍leetcode169---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.

该题类似于编程之美中的《寻找发帖水王》问题,出现数目都是超过了总数的一半,解法相同。解法一参见 http://blog.csdn.net/will130/article/details/46005287

问题求解:

解法一:O(n) time O(1) space

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution { public: int majorityElement(vector<int>& nums) { int n=nums.size(); int candidate, nTimes;//数组中的数和次数 for(int i=0, nTimes=0;i<n;i++) { if(nTimes==0) { candidate = nums[i], nTimes=1; } else { if(candidate == nums[i]) { nTimes++; } else { nTimes--; } } } return candidate; } };

解法二:O(n) time O(1) space

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution { public: int majorityElement(vector<int>& nums) { int n=nums.size(); int candidate=nums[0], nTimes=1;//数组中的数和次数 for(int i=1;i<n;i++) { if(nums[i] == candidate) { nTimes++; } else { if(nTimes == 0) { candidate = nums[i]; nTimes = 1; } else { nTimes--; } } } return candidate; } };

最后

以上就是多情中心最近收集整理的关于leetcode169---Majority Element(数组中出现次数超过一半的数)的全部内容,更多相关leetcode169---Majority内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(86)

评论列表共有 0 条评论

立即
投稿
返回
顶部