leetcode_169_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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.


//vs2012测试代码
#include<iostream>
#include<vector>
//方法二:如果不随机会超时;同样思路,随机挑选一个元素,检查是否是多数元素。时间复杂度:Average:O(n)。期望查找次数 <2
using namespace std;

#define n 5

class Solution {
public:
    int majorityElement(vector<int> &num) 
	{
		while(1)
		{
			int randnum;
			int count=0;
			//1个元素时,num.size()-1为0。而rand()%0不合法,应该规避。
		    if(num.size()==1)
		        return num[0];
			randnum = rand() % (num.size()-1);
			for(int i=0; i<num.size(); i++)
			{
				if( num[i] == num[randnum])
					count++;
				if(count > num.size()/2)
				{
					cout<<num[i];
					return num[i];
				}
			}
		}
    }
};

int main()
{
	int a;
	vector<int> num;
	for(int i=0; i<n; i++)
	{
		cin>>a;
		num.push_back(a);
	}
	Solution lin;
	lin.majorityElement(num);
}

//方法一:每找出两个不同的element,就成对删除即count--,最终剩下的一定就是所求的。时间复杂度:O(n)
class Solution {
public:
    int majorityElement(vector<int> &num) {
		int element;
        int length=num.size();
		int count=0;
		for(int i=0; i<length; i++)
		{
			if(count == 0)
			{
				element=num[i];
				count=1;
			}
			else
			{
				if(num[i] == element)
					count++;
				else
					count--;
			}
		}
		cout<<element;
		return element;
    }
};

//方法二:随机挑选一个元素,检查是否是多数元素。时间复杂度:Average:O(n)。期望查找次数 <2
class Solution {
public:
    int majorityElement(vector<int> &num) {
    
		while(1)
		{
			int randnum;
			int count=0;
			//1个元素时,num.size()-1为0。而rand()%0不合法,应该规避。
		    if(num.size()==1)
		        return num[0];
			randnum = rand() % (num.size()-1);
			for(int i=0; i<num.size(); i++)
			{
				if( num[i] == num[randnum])
					count++;
				if(count > num.size()/2)
				{
					cout<<num[i];
					return num[i];
				}
			}
		}
    }
};

//方法:不随机,超时
class Solution {
public:
    int majorityElement(vector<int> &num) 
	{
        int length=num.size();
		vector<int> count;
		count.resize(length);
		count.assign(length,0);

		for(int i=0; i<length; i++)
		{
			for(int j=0; j<length; j++)
			{
				if(num[j] == num[i])
					count[i]++;
			}
			if(count[i] > length/2)
			{
				cout<<num[i];
				return num[i];
			}
		}
    }
};


你可能感兴趣的:(LeetCode,C++,array)