LeetCode 169. Majority Element
2017-03-17 20:36
417 查看
题目:
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
思路:
给定一个数组,有n个数 ,找出其中的一个出现次数大于n/2的数。
有一个比较笨的方法,用nums_new来记录不同的数,对应的fre来
并且fre的空间还有浪费,水平暂时只到这里,但是成功Accepted~
代码:
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
思路:
给定一个数组,有n个数 ,找出其中的一个出现次数大于n/2的数。
有一个比较笨的方法,用nums_new来记录不同的数,对应的fre来
并且fre的空间还有浪费,水平暂时只到这里,但是成功Accepted~
代码:
class Solution { public: int majorityElement(vector<int>& nums) { vector<int> nums_new;//记录nums中出现的不一样的数 vector<int> fre(nums.size());//记录与nums_new对应索引的那个数出现的次数, nums_new.push_back(nums[0]);//将第一个数push_back fre[0] = 1;//第一个数出现次数记1 for (int i = 1; i<nums.size(); ++i){//从第二个数开始循环到最后一个 int flag = 0;//用来标记这个数是否已经出现过,如果出现过,则flag=1 for (int j = 0; j<nums_new.size(); ++j){ if (nums[i] == nums_new[j]){//遍历nums_new,如果相等,则当前nums_new[j]对应的fre[j]+1 fre[j] += 1; flag = 1; } } if (flag == 0){//如果这个数没出现过,即flag==0,将这个数push_back,对应的fre[index]+1 nums_new.push_back(nums[i]); fre[nums_new.size() - 1] += 1; } } for (int k = 0; k<fre.size(); ++k){ if (fre[k]>(nums.size() / 2)){//遍历fre,找出出现次数大于n/2的数并返回 return nums_new[k]; break; } } } };
相关文章推荐
- leetcode 169. Majority Element
- leetcode169 Majority Element
- [leetcode] 169. Majority Element
- LeetCode:169. Majority Element
- [LeetCode] 169. Majority Element
- LeetCode--169. Majority Element (Divide-and-Conquer)
- 【LeetCode】169. Majority Element(Easy)解题报告
- [LeetCode]169 Majority Element
- [leetcode 169] Majority Element
- 169 Majority Element [LeetCode Java实现]
- [LeetCode][169][Majority Element]
- leetcode 169 Majority Element
- 算法分析与设计:leetcode169.Majority Element
- leetcode 169. Majority Element 摩尔投票法
- [Leetcode 169, Easy] Majority Element
- 2018.03.07 leetcode 打卡 #169. Majority Element
- LeetCode 169 : Majority Element
- 【leetcode】169. Majority Element
- LeetCode 169. Majority Element
- leetcode 169. Majority Element 多数投票算法(Boyer-Moore Majority Vote algorithm)