leetcode169: 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.

解题思路:

solution1:统计出数组中每个元素出现的次数,出现次数最多的即为所求。一开始使用2重循环,不管元素重不重复都统计次数,去leetcode上检测“Time Limit Exceeded”。

solution2::用桶排序来统计元素次数,下面贴的代码,在本地编译器上测试没问题,去leetcode上检测“Runtime Error”。

#include<iostream>
#include<cmath>
#include<vector>
using namespace std;

int majorityElement(vector<int>& nums) {
	int length = nums.size();  
	
	// calculate the count the majorityElement should appear
	int number = 0;
	if (length % 2) {
		number = (length - 1) / 2;
	} else {
		number = length / 2;
	}
	
	int max = 0;
	for (int i = 0; i < length; i++) {
		// the element in the vector might be non-positive
        if (abs(nums[i]) > max) {
            max = abs(nums[i]);
        }
    }
    
	int size1 = 2*max + 1;
	int count[size1];
	for (int i = 0; i < size1; i++) {
		count[i] = 0;
	}
	
	
	
	for (int i = 0; i < length; i++) {
		if (nums[i] < 0) {
			count[size1 + nums[i]]++;
			if (count[size1 + nums[i]] > number) {
			return nums[i];
			}
		} else {
			count[nums[i]]++;
			if (count[nums[i]] > number) {
			return nums[i];
			}
		}
	}
// 把桶排的数组大小缩一半也没有用
	/*
	int size1 = max + 1;
	int count[size1];
	for (int i = 0; i < size1; i++) {
		count[i] = 0;
	}
	
	int count1 = 0, max1;
	int count2 = 0, max2;
	for (int i = 0; i < length; i++) {
		if (nums[i] > 0 || nums[i] == 0) {
			count[nums[i]]++;
			if (count[nums[i]] > count1) {
			    count1 = count[nums[i]];
			    max1 = nums[i];
			    if (count1 > number) {
			    	return max1;
				}
			}
		}
	}
	for (int i = 0; i < length; i++) {
		if (nums[i] < 0) {
			count[size1 + nums[i]]++;
			if (count[size1 + nums[i]] > count2) {
			    count2 = count[size1 + nums[i]];
			    max2 = nums[i];
			    if (count2 > number) {
			    	return max2;
				}
			}
		}
	}
	*/
}

int main() {
	int n, temp;
	cin >> n;
	vector<int> nums;
	for (int i = 0; i < n; i++) {
		cin  >> temp;
		nums.push_back(temp);
	}
	cout << majorityElement(nums);
	return 0;
}

 
solution3:使用STL容器 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值