持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第15天,点击查看活动详情
一:幸运的袋子
题目:题目描述
- 代码:
#include<iostream>
#include<algorithm>
using namespace std;
int get(int* arr,int n,int pos,int add,int multi) //pos:访问到的位置 add:加到了多少 multi; 乘到了多少
{
int count =0;
for(int i=pos;i<n;i++)
{
add+=arr[i];
multi*=arr[i];
if(add > multi) //假如add > multi , 该条件满足,并且往下面找满足的条件
{
count+=1+ get(arr,n, i+1,add,multi);
}
else if(arr[i]==1) //假如arr[i]==1 ,则该条件无效, 向后面找寻有效条件
count+= get(arr,n, i+1,add,multi);
else
break;
add-=arr[i];
multi/=arr[i];
while (i < n - 1 && arr[i] == arr[i + 1]) //将相同项移出,不再假如循环
{
i++;
}
}
return count;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
sort(arr,arr+n); //先将数组排序
cout<< get(arr,n,0,0,1);
return 0;
}
- 思路:
- 利用到了一个数学结论: 对于任意两个正整数a,b如果满足 a+b>a*b,则必有一个数为1.
- 基于这个结论,我们先将数组排好序,进入函数
- 看注释
二: 06-散列查找1 电话聊天狂人
-
题目:
-
代码:
#include<iostream>
#include<vector>
#include<map>
using namespace std;
int main()
{
map<long long, long long, greater<long long>> a; //利用map来记录,注意仿函数要用 greater<long long> 的,要将最小的在后面再访问
int n;
cin >> n;
while (n--)
{
long long tem;
cin >> tem;
a[tem]++;
cin >> tem;
a[tem]++;
}
unsigned long long max = 0, ret = -1;
int count = 0;
for (auto& e : a)
{
if (max < e.second)
{
max = e.second;
ret = e.first;
count = 1; //注意
}
else if (max == e.second)
{
ret = e.first; //因为仿函数是greater<long long>,如果出现次数相同,则后面出现的必然会更小
count++;
}
}
cout << ret << " " << max;
if (count > 1)
cout << " " << count;
}
思路看注释
- 注意:
- 千万不要惯性思维的去想成你曾经做过的题目,会将题目想复杂了
- 要根据题目的意思来 想 怎么样去实现 题目的要求 ,而不是根据自己之前写类似题的经验来做。
三:前K个高频单词
- 前K个高频单词:(题目链接)
- 代码:
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
//sort不稳定,堆排序也一样
//用两个map来排序
map<string,int> countMap;
for(auto& e: words)
{
countMap[e]++;
}
multimap<int,string,greater<int>> Map; //必须要用multimap,不然出现次数相同的string会被抵消掉
for(auto& e:countMap )
{
Map.insert(make_pair(e.second,e.first));
}
auto it = Map.begin();
vector<string> v;
while(k--)
{
v.push_back(it->second);
it++;
}
return v;
}
};
- 思路:
- 用一个map按字典序排字符串,并且记录出现次数
- 再用一个multimap来排序出现次数,并且记录字符串
- 利用迭代器来输出前k大的数
- 注意:
- 不能使用sort和堆来排序,因为不稳定
- 注意第二个map必须要用multimap,不然出现次数相同的string会被抵消掉
- multimap<int,string,greater> Map; ,注意是greater