力扣刷题总结 -- 数组4

10. 多数元素(简单)

题目要求:

给定一个大小为n的数组nums,返回其中的多数元素。多数元素是指在数组中出现次数大于n/2的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。

题目分析:

考虑使用键值对存放元素值和其相应的出现次数,map容器即可。

题目解答:

#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include<unordered_map>
#include <algorithm>


class Solution
{
public:
	int majorityElement(vector<int>& nums)
	{
		unordered_map<int, int> counts;  // 创建无顺序的map
		int majority = 0;  // 初始化多数
		int cnt = 0;  // 初始化元素的出现次数

		for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++)
		{
			++counts[*it];  // 该元素出现一次则加1

			if (counts[*it] > cnt)  // 如果当前元素出现的次数大于之前元素出现的最大次数
			{
				majority = *it;  // 将该元素值赋给majority
				cnt = counts[*it];  // 将该元素的出现次数赋值给cnt
			}
		}


		return majority;
	}

};


int main()
{
	vector<int> nums = { 2,2,1,1,1,2,2 };

	Solution s;
	int major = s.majorityElement(nums);

	cout << "数组中的多数为:" << major << endl;


	system("pause");
	return 0;
}

11. 存在重复元素(简单)

题目要求:

给定一个整数数组nums。如果任一值在数组中出现至少两次,返回true ;如果数组中每个元素互不相同,返回 false 。

题目分析:

直接将数组进行冒泡排序后遍历,若左右两个元素相等,则返回true,反之返回false。

题目解答:

#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include<unordered_map>
#include <algorithm>


class Solution
{
public:
	bool containsDuplicate(vector<int>& nums)
	{
		sort(nums.begin(), nums.end());  // 将数组重排序

		for (int i = 0; i < nums.size() - 1; i++)
		{
			if (nums[i] == nums[i + 1])
			{
				return true;
			}
		}

		return false;
	}

};


int main()
{
	vector<int> nums = { 1, 2, 3, 1 };

	Solution s;
	bool flag = s.containsDuplicate(nums);

	if (flag == true)
	{
		cout << "数组中存在重复元素!" << endl;
	}
	else
	{
		cout << "数组中没有重复元素!" << endl;
	}


	system("pause");
	return 0;
}

12. 存在重复元素II(简单)

题目要求:

给定一个整数数组nums和一个整数k,判断数组中是否存在两个不同的索引 i 和 j ,满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在,返回 true;否则,返回 false 。

题目分析:

使用map的count方法,该方法查找map中的元素,若元素存在返回1,否则返回0
利用for循环将nums中的元素逐个放入map容器中

题目解答:

#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include<unordered_map>
#include <algorithm>


class Solution
{
public:
	bool containNearbyDuplicate(vector<int>& nums, int k)
	{
		unordered_map<int, int> dict;

		for (int i = 0; i < nums.size(); i++)
		{
			int num = nums[i];

			// 如果map中第二次出现了该元素,且第二次出现元素的索引和第一次出现元素的索引之差<=k,则返回true
			if (dict.count(num) && (i - dict[num] <= k))
			{
				return true;
			}
			dict[num] = i;  // 若此时nums中的num元素还不在dict中,则赋值
		}

		return false;
	}

};


int main()
{
	vector<int> nums = { 1,2,3,1,2,3 };
	Solution s;

	bool flag = s.containNearbyDuplicate(nums, 2);
	if (flag == true)
	{
		cout << "数组中存在指定的重复元素!" << endl;
	}
	else
	{
		cout << "数组中没有指定的重复元素!" << endl;
	}


	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值