力扣169. 多数元素

Problem: 169. 多数元素

题目描述

在这里插入图片描述

思路

1.哈希表

将数组中的每个元素作为,其出现的次数作为存入哈希表中,最终找出多数元素

2.排序

将数组进行升序排序,由于多数元素大于数组长度的一半,则排序后的数组中的中间位置一定是多数元素

复杂度

思路1:
时间复杂度:

O ( n ) O(n) O(n);其中 n n n是数组nums的大小

空间复杂度:

O ( n ) O(n) O(n)

思路2:
时间复杂度:

O ( n l o g n ) O(nlogn) O(nlogn)

空间复杂度:

O ( 1 ) O(1) O(1)

Code

思路1:

class Solution {
public:
	/// <summary>
	/// Gets the majority of the elements in the array
	/// </summary>
	/// 
	/// <param name="nums"> Given array </param>
	/// <returns> int </returns>
	int majorityElement(vector<int>& nums) {
		unordered_map<int, int> map;
		for (int i = 0; i < nums.size(); ++i) {
			if (map.find(nums[i]) != map.end()) {
				map[nums[i]] = 1;
			} else {
				map[nums[i]] = map[nums[i]] + 1;
			}
		}
		for (auto it = map.begin(); it != map.end(); ++it) {
			if (it->second > (nums.size() / 2)) {
				return it->first;
			}
		}
		return -1;
	}
};

思路2:

class Solution {
public:
	/// <summary>
	/// Gets the majority of the elements in the array
	/// </summary>
	/// 
	/// <param name="nums"> Given array </param>
	/// <returns> int </returns>
	int majorityElement(vector<int>& nums) {
		sort(nums.begin(), nums.end());
		return nums[nums.size() / 2];
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值