首页 > 代码库 > 【Lintcode】046.Majority Number
【Lintcode】046.Majority Number
题目:
Given an array of integers, the majority number is the number that occurs more than half
of the size of the array. Find it.
Notice
You may assume that the array is non-empty and the majority number always exist in the array.
Have you met this question in a real interview?
Yes
Example
Given [1, 1, 1, 1, 2, 2, 2]
, return 1
题解:
摩尔投票法
Solution 1 ()
class Solution { public: int majorityNumber(vector<int> nums) { int cnt = 0; int res = nums[0]; for(auto n : nums) { if (n == res) { cnt++; continue; } else { if(--cnt <= 0) { cnt = 1; res = n; } } } return res; } };
【Lintcode】046.Majority Number
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。