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;
}