Skip to content

Commit 9f7407f

Browse files
committed
summary-ranges.cc & majority-element-ii.cc
1 parent 5f6b890 commit 9f7407f

File tree

3 files changed

+43
-1
lines changed

3 files changed

+43
-1
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
[LeetCode solutions](http://maskray.me/blog/2014-06-29-leetcode-solutions) gives some thoughts on selected problems.
44

5-
Solved 202/211 problems.
5+
Solved 204/213 problems.
66

77
## Database
88

@@ -12,6 +12,8 @@ See [database.md](database.md)
1212

1313
| # | Title | Solution |
1414
|---| ----- | -------- |
15+
|229|[Majority Element II](/problems/majority-element-ii/)|[majority-element-ii.cc](majority-element-ii.cc)|
16+
|228|[Summary Ranges](/problems/summary-ranges/)|[summary-ranges.cc](summary-ranges.cc)|
1517
|227|[Basic Calculator II](/problems/basic-calculator-ii/)|[basic-calculator-ii.cc](basic-calculator-ii.cc)|
1618
|226|[Invert Binary Tree](/problems/invert-binary-tree/)|[invert-binary-tree.cc](invert-binary-tree.cc)|
1719
|225|[Implement Stack using Queues](/problems/implement-stack-using-queues/)|[implement-stack-using-queues.cc](implement-stack-using-queues.cc)|

majority-element-ii.cc

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Majority Element II
2+
class Solution {
3+
public:
4+
vector<int> majorityElement(vector<int> &a) {
5+
int y = 0, z = 1, cy = 0, cz = 0;
6+
for (auto x: a) {
7+
if (x == y) cy++;
8+
else if (x == z) cz++;
9+
else if (! cy) y = x, cy = 1;
10+
else if (! cz) z = x, cz = 1;
11+
else cy--, cz--;
12+
}
13+
cy = cz = 0;
14+
for (auto x: a)
15+
if (x == y) cy++;
16+
else if (x == z) cz++;
17+
vector<int> r;
18+
if (cy > a.size()/3) r.push_back(y);
19+
if (cz > a.size()/3) r.push_back(z);
20+
return r;
21+
}
22+
};

summary-ranges.cc

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Summary Ranges
2+
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
3+
#define REP(i, n) FOR(i, 0, n)
4+
5+
class Solution {
6+
public:
7+
vector<string> summaryRanges(vector<int> &a) {
8+
vector<string> r;
9+
int s = 0, n = (int)a.size();
10+
REP(i, n) {
11+
if (i == n-1 || a[i]+1 != a[i+1]) {
12+
r.push_back(s == i ? to_string(a[i]) : to_string(a[s])+"->"+to_string(a[i]));
13+
s = i+1;
14+
}
15+
}
16+
return r;
17+
}
18+
};

0 commit comments

Comments
 (0)