classSolution { public: boolisNStraightHand(vector<int>& hand, int W){ int n = hand.size(); if (n%W) returnfalse; map<int, int> count; for (auto x : hand) count[x]++; while (count.size()) { int start = count.begin()->first; for (int i = start; i < start+W; ++i) { if (count.find(i) == count.end()) returnfalse; if (!--count[i]) count.erase(i); } } returntrue; } };
排序统计(c++)
classSolution { public: boolisNStraightHand(vector<int>& hand, int W){ int n = hand.size(); if (n%W) returnfalse; if (W==1) returntrue; sort(hand.begin(), hand.end()); vector<int> vis(n, 0); for (int i = 0; i < n; ++i) { if (vis[i]) continue; int cnt = 1; vis[i] = 1; for (int j = i+1; j < n; ++j) { if (hand[j]>hand[i]+cnt) break; if (!vis[j] && hand[j]==hand[i]+cnt) { vis[j] = 1; cnt++; if (cnt == W) break; } } if (cnt != W) returnfalse; } returntrue; } };
排序统计2,来自于网友zhanzq(c++)
classSolution { public: boolvalid(vector<int> &lst, int W){ lst.push_back(0); int sz = lst.size(); int pre = 0; vector<int> deltas(sz, 0); for(int i = 0; i < sz; i++){ pre += deltas[i]; if(pre < lst[i]){ int delta = lst[i] - pre; pre = lst[i]; if(i + W < sz){ deltas[i+W] -= delta; } }elseif(pre > lst[i]){ returnfalse; } } returntrue; }