LeetCode 169. Majority Element

来源:互联网 发布:网络系统工程师简历 编辑:程序博客网 时间:2024/06/07 23:49

题目:

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_backfre[0] = 1;//第一个数出现次数记1for (int i = 1; i<nums.size(); ++i){//从第二个数开始循环到最后一个int flag = 0;//用来标记这个数是否已经出现过,如果出现过,则flag=1for (int j = 0; j<nums_new.size(); ++j){if (nums[i] == nums_new[j]){//遍历nums_new,如果相等,则当前nums_new[j]对应的fre[j]+1fre[j] += 1;flag = 1;}}if (flag == 0){//如果这个数没出现过,即flag==0,将这个数push_back,对应的fre[index]+1nums_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;}}}};


0 0