码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_169题——Majority Element(采用的map来做的)

时间:2015-05-03 18:51:52      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

Majority Element

 Total Accepted: 35645 Total Submissions: 103047My Submissions

 

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.

 

Hide Tags
 Divide and Conquer Array Bit Manipulation
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

      这道题的要求是找到行向量中出现次数最多的数字,而在题目中好像希望可以用分治法来做,但是我采用的map来做的,因为这个记录起来很快,map查找的时间复杂度很小,<int,int> first中储存值。second储存值出现的次数

#include<iostream>
#include <vector>
#include <map>
#include <utility>
using namespace std;

int majorityElement(vector<int>& nums) {
	map<int,int> temp;
	int len=nums.size();
	int result;
	if(len==1)
	{
		result=nums[0];
		return result;
	}
	for(int i=0;i<len;i++)
	{
		if(temp.count(nums[i])==0)
		{
			temp.insert(make_pair(nums[i],1));
		}
		else
		{
			temp[nums[i]]++;
		}
	}
	pair<int,int>max_num(temp.begin()->first,temp.begin()->second);
	for(map<int,int>::iterator i=temp.begin();i!=temp.end();i++)
	{
		if(i->second>max_num.second)
		{
			max_num.first=i->first;
			max_num.second=i->second;
		}
	}
	result=max_num.first;
	return result;
}
int main()
{
	vector<int> vec;
	vec.push_back(2),vec.push_back(2);
	cout<<majorityElement(vec)<<endl;
}

  

leetcode_169题——Majority Element(采用的map来做的)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4474353.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!