leetcode 846.Hand of Straights
2024-10-10 04:37:04
对于一个数组中的数分为W组且在每一组内的数是连续存在的。
考虑使用map映射来记录每个数的个数的,并且对于数组中的数进行从小到大的排列的。同时每次需要更新最开始的那个起始数的,可能是以及出现的也可能是没有出现过的,这些都是需要考虑到的。
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int W) {
int n=hand.size();
if(n%W!=) return false;
map<int,int> m;
for(int i=;i<n;i++){
if(!m.count(hand[i])){
m[hand[i]]=;
}else{
m[hand[i]]++;
}
}
sort(hand.begin(),hand.end());
//int cnt=0;
int start=hand[];
for(int i=;i<n/W;i++){
//int start=hand[cnt];
for(int j=;j<W;j++){
cout<<start+j<<endl;
if(!m.count(start+j))
return false;
m[start+j]--;
if(m[start+j]<)
return false;
}
int flag=; // 考虑如果所有的数都被用完的话就需要取得新的数的
for(int j=;j<W;j++){
if(m[start+j]!=){
start=start+j;
flag=;
break;
}
}
if(!flag){
start=hand[(i+)*W];
}
}
return true;
}
};
其实是可以不用排序的,因为map本身就会按照关键字进行排序的,并且需要满足其数量相等的即可的。
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int W) {
int n=hand.size();
if(n%W!=) return false; map<int, int> m;
for(int i=;i<n;i++) m[hand[i]]++; map<int,int>::iterator it;
for(it=m.begin();it!=m.end();it++){
int n=it->second;
if(n!=){
for(int i=it->first; i<it->first+W; i++){
if(!m.count(i) || m[i]<n)
return false;
m[i]-=n;
}
}
}
return true;
}
};
最新文章
- 常用的js正则表达式
- .NET C# 将 mdb 中数据读为 list<;string[]>; 其中 path 为数据库地址 ,sql 为查询语句
- [转]jquery 对 Json 的各种遍历
- 把int放在一个char数组里(用于处理每一位数字)
- iOS学习笔记---oc语言第六天
- 【转】UIBezierPath精讲
- Java中如何把两个数组合并为一个
- setImageResource与setImageBitmap的区别
- 翻译:MariaDB wait/nowait
- 开博近一年的感想 by 程序员小白
- Python返回Json格式定义的例子
- 【BZOJ4827】【HNOI2017】礼物(FFT)
- Summer sell-off CodeForces - 810B (排序后贪心)
- centos 7 su jenkins 切换不过去
- 用PNChart绘制折线图
- ubuntu18.04 安装新版本openssl
- 机器学习入门-文本数据-构造Tf-idf词袋模型(词频和逆文档频率) 1.TfidfVectorizer(构造tf-idf词袋模型)
- <;compilation debug=";true"; targetFramework=";4.5";>; 报错解决方案
- [LeetCode] 243. Shortest Word Distance_Easy
- mathematica里面清除全部变量