cpp(chore): add clang-format style and format

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-01-03 12:06:42 +01:00
parent 2daade49c0
commit b229608723
Signed by: mfocko
GPG key ID: 7C47D46246790496
50 changed files with 870 additions and 846 deletions

235
cpp/.clang-format Normal file
View file

@ -0,0 +1,235 @@
---
Language: Cpp
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
PadOperators: true
AlignConsecutiveBitFields:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
PadOperators: false
AlignConsecutiveDeclarations:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
PadOperators: false
AlignConsecutiveMacros:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
PadOperators: false
AlignConsecutiveShortCaseStatements:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCaseColons: false
AlignEscapedNewlines: Right
AlignOperands: Align
AlignTrailingComments:
Kind: Always
OverEmptyLines: 0
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine
AttributeMacros:
- __capability
BinPackArguments: true
BinPackParameters: true
BitFieldColonSpacing: Both
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterExternBlock: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakAfterAttributes: Never
BreakAfterJavaFieldAnnotations: false
BreakArrays: true
BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: Always
BreakBeforeBraces: Attach
BreakBeforeInlineASMColon: OnlyMultiline
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 1
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseBlocks: false
IndentCaseLabels: false
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true
IndentPPDirectives: None
IndentRequiresClause: true
IndentWidth: 4
IndentWrappedFunctionNames: false
InsertBraces: false
InsertNewlineAtEOF: false
InsertTrailingCommas: None
IntegerLiteralSeparator:
Binary: 0
BinaryMinDigits: 0
Decimal: 0
DecimalMinDigits: 0
Hex: 0
HexMinDigits: 0
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
KeepEmptyLinesAtEOF: false
LambdaBodyIndentation: Signature
LineEnding: DeriveLF
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PackConstructorInitializers: BinPack
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
PPIndentWidth: -1
QualifierAlignment: Leave
ReferenceAlignment: Pointer
ReflowComments: true
RemoveBracesLLVM: false
RemoveParentheses: Leave
RemoveSemicolon: false
RequiresClausePosition: OwnLine
RequiresExpressionIndentation: OuterScope
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SortIncludes: CaseSensitive
SortJavaStaticImport: Before
SortUsingDeclarations: LexicographicNumeric
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceAroundPointerQualifiers: Default
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeJsonColon: false
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDefinitionName: false
AfterFunctionDeclarationName: false
AfterIfMacros: true
AfterOverloadedOperator: false
AfterRequiresInClause: false
AfterRequiresInExpression: false
BeforeNonEmptyParentheses: false
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: Never
SpacesInContainerLiterals: true
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParens: Never
SpacesInParensOptions:
InCStyleCasts: false
InConditionalStatements: false
InEmptyParentheses: false
Other: false
SpacesInSquareBrackets: false
Standard: Latest
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 8
UseTab: Never
VerilogBreakBetweenInstancePorts: true
WhitespaceSensitiveMacros:
- BOOST_PP_STRINGIZE
- CF_SWIFT_NAME
- NS_SWIFT_NAME
- PP_STRINGIZE
- STRINGIZE
...

View file

@ -2,7 +2,7 @@
#include <vector>
class Solution {
public:
public:
int findContentChildren(std::vector<int> g, std::vector<int> s) {
std::sort(g.begin(), g.end());
std::sort(s.begin(), s.end());
@ -18,4 +18,3 @@ public:
return content;
}
};

View file

@ -2,9 +2,8 @@
#include <vector>
class Solution {
public:
int numRescueBoats(std::vector<int> people, int limit)
{
public:
int numRescueBoats(std::vector<int> people, int limit) {
std::sort(people.begin(), people.end());
int counter = 0;

View file

@ -1,5 +1,5 @@
class Solution {
public:
public:
int totalMoney(int n) {
auto monday = 1;

View file

@ -4,9 +4,8 @@
using std::vector;
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n)
{
public:
bool canPlaceFlowers(vector<int> &flowerbed, int n) {
int count = 0;
int left = 0, right;
@ -25,21 +24,20 @@ public:
}
};
int main()
{
int main() {
Solution s;
std::vector flowers { 1, 0, 0, 0, 1 };
std::vector flowers{1, 0, 0, 0, 1};
assert(s.canPlaceFlowers(flowers, 1));
assert(!s.canPlaceFlowers(flowers, 2));
flowers = { 1, 0, 0, 0, 0, 1 };
flowers = {1, 0, 0, 0, 0, 1};
assert(!s.canPlaceFlowers(flowers, 2));
flowers = { 1, 0, 0, 0, 1, 0, 0 };
flowers = {1, 0, 0, 0, 1, 0, 0};
assert(s.canPlaceFlowers(flowers, 2));
flowers = { 0, 0, 1, 0, 0 };
flowers = {0, 0, 1, 0, 0};
assert(s.canPlaceFlowers(flowers, 1));
return 0;

View file

@ -3,9 +3,8 @@
class Solution {
static const int MOD = 1000000007;
public:
int concatenatedBinary(int n)
{
public:
int concatenatedBinary(int n) {
long joined_number = 0;
int padding = 1;
@ -21,8 +20,7 @@ public:
}
};
int main()
{
int main() {
Solution s;
assert(s.concatenatedBinary(1) == 1);

View file

@ -2,8 +2,8 @@
#include <vector>
class Solution {
public:
std::vector<std::vector<int>> findMatrix(const std::vector<int>& nums) {
public:
std::vector<std::vector<int>> findMatrix(const std::vector<int> &nums) {
// count the numbers
std::map<int, int> freqs;
for (auto x : nums) {
@ -17,7 +17,7 @@ public:
elements_left = false;
std::vector<int> row;
for (auto& [num, count] : freqs) {
for (auto &[num, count] : freqs) {
if (count <= 0) {
continue;
}
@ -32,4 +32,3 @@ public:
return matrix;
}
};

View file

@ -6,23 +6,21 @@
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
int goodNodes(TreeNode* root, int m)
{
int goodNodes(TreeNode *root, int m) {
if (root == nullptr) {
return 0;
}
int new_max = std::max(m, root->val);
return (root->val >= m) + goodNodes(root->left, new_max) + goodNodes(root->right, new_max);
return (root->val >= m) + goodNodes(root->left, new_max) +
goodNodes(root->right, new_max);
}
public:
int goodNodes(TreeNode* root)
{
return goodNodes(root, INT_MIN);
}
public:
int goodNodes(TreeNode *root) { return goodNodes(root, INT_MIN); }
};

View file

@ -3,14 +3,14 @@
#include <vector>
class Solution {
public:
int countNegatives(const std::vector<std::vector<int>>& grid)
{
public:
int countNegatives(const std::vector<std::vector<int>> &grid) {
auto last = 0;
auto negatives = 0;
for (const auto& row : grid) {
auto first_positive = std::lower_bound(row.crbegin() + last, row.crend(), 0);
for (const auto &row : grid) {
auto first_positive =
std::lower_bound(row.crbegin() + last, row.crend(), 0);
auto i = first_positive - row.crbegin();
negatives += i;
@ -20,11 +20,13 @@ public:
}
};
int main()
{
int main() {
Solution s;
assert((s.countNegatives(std::vector { std::vector { 4, 3, 2, -1 }, std::vector { 3, 2, 1, -1 }, std::vector { 1, 1, -1, -2 }, std::vector { -1, -1, -2, -3 } }) == 8));
assert((s.countNegatives(std::vector { std::vector { 3, 2 }, std::vector { 1, 0 } }) == 0));
assert((s.countNegatives(std::vector{
std::vector{4, 3, 2, -1}, std::vector{3, 2, 1, -1},
std::vector{1, 1, -1, -2}, std::vector{-1, -1, -2, -3}}) == 8));
assert((s.countNegatives(
std::vector{std::vector{3, 2}, std::vector{1, 0}}) == 0));
return 0;
}

View file

@ -2,43 +2,43 @@
#include <vector>
class Solution {
constexpr static int MOD = 1000000007;
constexpr static int MOD = 1000000007;
static void add_with_mod(std::vector<int>& good, std::size_t i, int value) {
good[i] = (good[i] + value) % MOD;
}
public:
int countGoodStrings(int low, int high, int zero, int one) {
assert(low <= high);
std::vector<int> good(high + 1, 0);
good[0] = 1;
for (int length = 1; length <= high; ++length) {
if (length >= zero) {
add_with_mod(good, length, good[length - zero]);
}
if (length >= one) {
add_with_mod(good, length, good[length - one]);
}
static void add_with_mod(std::vector<int> &good, std::size_t i, int value) {
good[i] = (good[i] + value) % MOD;
}
int total = 0;
for (int i = low; i <= high; ++i) {
total = (total + good[i]) % MOD;
}
public:
int countGoodStrings(int low, int high, int zero, int one) {
assert(low <= high);
return total;
}
std::vector<int> good(high + 1, 0);
good[0] = 1;
for (int length = 1; length <= high; ++length) {
if (length >= zero) {
add_with_mod(good, length, good[length - zero]);
}
if (length >= one) {
add_with_mod(good, length, good[length - one]);
}
}
int total = 0;
for (int i = low; i <= high; ++i) {
total = (total + good[i]) % MOD;
}
return total;
}
};
int main() {
Solution s;
Solution s;
assert(s.countGoodStrings(3, 3, 1, 1) == 8);
assert(s.countGoodStrings(2, 3, 1, 2) == 5);
assert(s.countGoodStrings(3, 3, 1, 1) == 8);
assert(s.countGoodStrings(2, 3, 1, 2) == 5);
return 0;
return 0;
}

View file

@ -5,8 +5,7 @@ class ParkingSystem {
int medium;
int small;
int& get(int carType)
{
int &get(int carType) {
switch (carType) {
case 1:
return big;
@ -19,17 +18,12 @@ class ParkingSystem {
}
}
public:
public:
ParkingSystem(int big, int medium, int small)
: big(big)
, medium(medium)
, small(small)
{
}
: big(big), medium(medium), small(small) {}
bool addCar(int carType)
{
auto& space = get(carType);
bool addCar(int carType) {
auto &space = get(carType);
if (space <= 0) {
return false;
}

View file

@ -5,9 +5,8 @@
class Solution {
using freq_t = std::array<std::size_t, 26>;
freq_t freqs(const std::string& word)
{
freq_t f { 0 };
freq_t freqs(const std::string &word) {
freq_t f{0};
for (auto c : word) {
f[c - 'a']++;
@ -16,8 +15,7 @@ class Solution {
return f;
}
int mask(const freq_t& f)
{
int mask(const freq_t &f) {
int m = 0;
for (auto c : f) {
@ -27,9 +25,8 @@ class Solution {
return m;
}
public:
bool closeStrings(std::string word1, std::string word2)
{
public:
bool closeStrings(std::string word1, std::string word2) {
auto f1 = freqs(word1);
auto m1 = mask(f1);
std::sort(f1.begin(), f1.end());

View file

@ -3,21 +3,19 @@
#include <vector>
class Solution {
public:
char nextGreatestLetter(const std::vector<char>& letters, char target)
{
public:
char nextGreatestLetter(const std::vector<char> &letters, char target) {
auto it = std::lower_bound(letters.begin(), letters.end(), target + 1);
return it == letters.end() ? letters.front() : *it;
}
};
int main()
{
int main() {
Solution s;
assert((s.nextGreatestLetter(std::vector { 'c', 'f', 'j' }, 'a') == 'c'));
assert((s.nextGreatestLetter(std::vector { 'c', 'f', 'j' }, 'c') == 'f'));
assert((s.nextGreatestLetter(std::vector { 'x', 'x', 'y', 'y' }, 'z') == 'x'));
assert((s.nextGreatestLetter(std::vector{'c', 'f', 'j'}, 'a') == 'c'));
assert((s.nextGreatestLetter(std::vector{'c', 'f', 'j'}, 'c') == 'f'));
assert((s.nextGreatestLetter(std::vector{'x', 'x', 'y', 'y'}, 'z') == 'x'));
return 0;
}

View file

@ -20,7 +20,7 @@ class Solution {
static int add(int x, int y) { return (x + y) % 1000000007; }
static int get(const std::vector<pad_t>& dp, int it, int idx) {
static int get(const std::vector<pad_t> &dp, int it, int idx) {
if (it < 0 || it >= static_cast<int>(dp.size())) {
return 0;
}
@ -32,7 +32,7 @@ class Solution {
return dp[it][idx];
}
static void dpIteration(std::vector<pad_t>& dp, int it) {
static void dpIteration(std::vector<pad_t> &dp, int it) {
for (int i = 0; i < 12; ++i) {
if (!isValidMove(i)) {
continue;
@ -59,7 +59,7 @@ class Solution {
}
}
public:
public:
int knightDialer(int n) {
std::vector<pad_t> dp(n);

View file

@ -6,9 +6,8 @@
using namespace std;
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k)
{
public:
int kthSmallest(vector<vector<int>> &matrix, int k) {
int low = matrix.front().front();
int high = matrix.back().back();
@ -16,7 +15,7 @@ public:
int mid = low + (high - low) / 2;
int rank = 0;
for (const auto& row : matrix) {
for (const auto &row : matrix) {
rank += upper_bound(row.begin(), row.end(), mid) - row.begin();
}
@ -31,22 +30,17 @@ public:
}
};
int main()
{
int main() {
Solution s;
vector<vector<int>> m;
int k;
m = {
{ 1, 5, 9 },
{ 10, 11, 13 },
{ 12, 13, 15 }
};
m = {{1, 5, 9}, {10, 11, 13}, {12, 13, 15}};
k = 8;
assert(s.kthSmallest(m, k) == 13);
m = { { -5 } };
m = {{-5}};
k = 1;
assert(s.kthSmallest(m, k) == -5);
}

View file

@ -1,8 +1,8 @@
#include <string>
class Solution {
public:
std::string largestOddNumber(const std::string& num) {
public:
std::string largestOddNumber(const std::string &num) {
auto i = num.find_last_of("13579");
if (i == std::string::npos) {
return "";

View file

@ -2,45 +2,47 @@
#include <vector>
class Solution {
struct indices {
int x;
int y;
struct indices {
int x;
int y;
bool operator==(const indices& other) const = default;
indices& operator+=(const indices& other) {
x += other.x;
y += other.y;
return *this;
bool operator==(const indices &other) const = default;
indices &operator+=(const indices &other) {
x += other.x;
y += other.y;
return *this;
}
int operator[](const std::vector<std::vector<int>> &mat) const {
return mat[y][x];
}
};
public:
int diagonalSum(const std::vector<std::vector<int>> &mat) {
int sum = 0;
indices down{0, 0}, up{0, static_cast<int>(mat.size()) - 1};
indices d_down{1, 1}, d_up{1, -1};
for (std::size_t i = 0; i < mat.size();
++i, down += d_down, up += d_up) {
sum += down[mat];
if (down != up) {
sum += up[mat];
}
}
return sum;
}
int operator[](const std::vector<std::vector<int>>& mat) const {
return mat[y][x];
}
};
public:
int diagonalSum(const std::vector<std::vector<int>>& mat) {
int sum = 0;
indices down{0, 0}, up{0, static_cast<int>(mat.size()) - 1};
indices d_down{1, 1}, d_up{1, -1};
for (std::size_t i = 0; i < mat.size(); ++i, down += d_down, up += d_up) {
sum += down[mat];
if (down != up) {
sum += up[mat];
}
}
return sum;
}
};
int main() {
Solution s;
Solution s;
assert((s.diagonalSum({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}) == 25));
assert((s.diagonalSum(
{{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}}) == 8));
assert((s.diagonalSum({{5}}) == 5));
return 0;
assert((s.diagonalSum({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}) == 25));
assert(
(s.diagonalSum(
{{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}}) == 8));
assert((s.diagonalSum({{5}}) == 5));
return 0;
}

View file

@ -2,15 +2,14 @@
#include <vector>
class Solution {
void row_partial_sums(const std::vector<std::vector<int>>& matrix, std::size_t y, std::vector<int>& partial) const
{
void row_partial_sums(const std::vector<std::vector<int>> &matrix,
std::size_t y, std::vector<int> &partial) const {
for (std::size_t x = 0; x < partial.size(); x++) {
partial[x] += matrix[y][x];
}
}
int find(std::vector<int>& partial_sums, int k) const
{
int find(std::vector<int> &partial_sums, int k) const {
int max_sum = INT_MIN;
std::set<int> prefixes;
@ -31,9 +30,9 @@ class Solution {
return max_sum;
}
public:
int maxSumSubmatrix(const std::vector<std::vector<int>>& matrix, int k) const
{
public:
int maxSumSubmatrix(const std::vector<std::vector<int>> &matrix,
int k) const {
std::size_t rows = matrix.size();
std::size_t cols = matrix.front().size();

View file

@ -1,8 +1,7 @@
#include <cassert>
namespace {
long sum(long index, long value, long n)
{
long sum(long index, long value, long n) {
long count = 0;
if (value > index) {
@ -19,12 +18,11 @@ long sum(long index, long value, long n)
return count - value;
}
}
} // namespace
class Solution {
public:
int maxValue(int n, int index, int maxSum)
{
public:
int maxValue(int n, int index, int maxSum) {
int left = 1, right = maxSum;
while (left < right) {
@ -40,8 +38,7 @@ public:
}
};
int main()
{
int main() {
Solution s;
assert(s.maxValue(4, 2, 6) == 2);

View file

@ -2,9 +2,9 @@
#include <string>
class Solution {
public:
std::string mergeAlternately(const std::string& word1, const std::string& word2)
{
public:
std::string mergeAlternately(const std::string &word1,
const std::string &word2) {
std::string result;
auto l = word1.begin();
@ -27,8 +27,7 @@ public:
}
};
int main()
{
int main() {
Solution s;
assert(s.mergeAlternately("abc", "pqr") == "apbqcr");

View file

@ -9,9 +9,8 @@
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head)
{
public:
ListNode *middleNode(ListNode *head) {
auto slow = head;
auto fast = head ? head->next : nullptr;

View file

@ -2,13 +2,12 @@
#include <tuple>
class Solution {
public:
int minFlips(int a, int b, int c)
{
public:
int minFlips(int a, int b, int c) {
auto flips = 0;
for (; (a | b) != c; a >>= 1, b >>= 1, c >>= 1) {
auto [aa, bb, cc] = std::tuple { a & 1, b & 1, c & 1 };
auto [aa, bb, cc] = std::tuple{a & 1, b & 1, c & 1};
if ((aa | bb) == cc) {
continue;
@ -25,8 +24,7 @@ public:
}
};
int main()
{
int main() {
Solution s;
assert(s.minFlips(2, 6, 5) == 3);

View file

@ -1,7 +1,6 @@
class Solution {
public:
int mirrorReflection(int p, int q)
{
public:
int mirrorReflection(int p, int q) {
auto lcm = p * q / std::gcd(p, q);
auto x = lcm / p;
auto y = lcm / q;

View file

@ -8,25 +8,20 @@ struct range_t {
int start;
int end;
range_t(int start, int end)
: start(start)
, end(end)
{
}
range_t(int start, int end) : start(start), end(end) {}
bool has(int x) const { return x > start && x < end; }
bool operator>(const range_t& other) const { return start > other.start; }
bool operator>(const range_t &other) const { return start > other.start; }
bool operator==(const range_t& other) const
{
bool operator==(const range_t &other) const {
return start == other.start && end == other.end;
}
};
bool overlaps(const range_t& a, const range_t& b)
{
return a == b || a.has(b.start) || a.has(b.end) || b.has(a.start) || b.has(a.end);
bool overlaps(const range_t &a, const range_t &b) {
return a == b || a.has(b.start) || a.has(b.end) || b.has(a.start) ||
b.has(a.end);
}
} // namespace
@ -34,11 +29,10 @@ bool overlaps(const range_t& a, const range_t& b)
class MyCalendar {
std::vector<range_t> entries;
public:
public:
MyCalendar() = default;
bool book(int start, int end)
{
bool book(int start, int end) {
entries.emplace_back(start, end);
auto it = entries.end();
@ -69,15 +63,14 @@ public:
* bool param_1 = obj->book(start,end);
*/
static void test_case_1()
{
static void test_case_1() {
std::cout << "=== TEST CASE 1 ===\n";
std::vector<range_t> entries { { 47, 50 }, { 33, 41 }, { 39, 45 }, { 33, 42 },
{ 25, 32 }, { 26, 35 }, { 19, 25 }, { 3, 8 },
{ 8, 13 }, { 18, 27 } };
std::vector<bool> expected { true, true, false, false, true,
false, true, true, true, false };
std::vector<range_t> entries{{47, 50}, {33, 41}, {39, 45}, {33, 42},
{25, 32}, {26, 35}, {19, 25}, {3, 8},
{8, 13}, {18, 27}};
std::vector<bool> expected{true, true, false, false, true,
false, true, true, true, false};
MyCalendar c;
for (auto i = 0; i < entries.size(); i++) {
@ -90,12 +83,12 @@ static void test_case_1()
}
}
static void test_case_2()
{
static void test_case_2() {
std::cout << "=== TEST CASE 2 ===\n";
std::vector<range_t> entries { { 37, 50 }, { 33, 50 }, { 4, 17 }, { 35, 48 }, { 8, 25 } };
std::vector<bool> expected { true, false, true, false, false };
std::vector<range_t> entries{
{37, 50}, {33, 50}, {4, 17}, {35, 48}, {8, 25}};
std::vector<bool> expected{true, false, true, false, false};
MyCalendar c;
for (auto i = 0; i < entries.size(); i++) {
@ -108,22 +101,19 @@ static void test_case_2()
}
}
static void test_case_3()
{
static void test_case_3() {
std::cout << "=== TEST CASE 3 ===\n";
std::vector<range_t> entries {
{ 20, 29 }, { 13, 22 }, { 44, 50 }, { 1, 7 }, { 2, 10 }, { 14, 20 },
{ 19, 25 }, { 36, 42 }, { 45, 50 }, { 47, 50 }, { 39, 45 }, { 44, 50 },
{ 16, 25 }, { 45, 50 }, { 45, 50 }, { 12, 20 }, { 21, 29 }, { 11, 20 },
{ 12, 17 }, { 34, 40 }, { 10, 18 }, { 38, 44 }, { 23, 32 }, { 38, 44 },
{ 15, 20 }, { 27, 33 }, { 34, 42 }, { 44, 50 }, { 35, 40 }, { 24, 31 }
};
std::vector<bool> expected {
true, false, true, true, false, true, false, true, false, false,
std::vector<range_t> entries{
{20, 29}, {13, 22}, {44, 50}, {1, 7}, {2, 10}, {14, 20},
{19, 25}, {36, 42}, {45, 50}, {47, 50}, {39, 45}, {44, 50},
{16, 25}, {45, 50}, {45, 50}, {12, 20}, {21, 29}, {11, 20},
{12, 17}, {34, 40}, {10, 18}, {38, 44}, {23, 32}, {38, 44},
{15, 20}, {27, 33}, {34, 42}, {44, 50}, {35, 40}, {24, 31}};
std::vector<bool> expected{
true, false, true, true, false, true, false, true, false, false,
false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false
};
false, false, false, false, false, false, false, false, false, false};
MyCalendar c;
for (auto i = 0; i < entries.size(); i++) {
@ -136,8 +126,7 @@ static void test_case_3()
}
}
int main()
{
int main() {
MyCalendar c;
assert(c.book(10, 20));
assert(!c.book(15, 25));

View file

@ -21,8 +21,7 @@ public:
*/
class Solution {
void levelOrder(vector<vector<int>>& traversal, Node* root, int level)
{
void levelOrder(vector<vector<int>> &traversal, Node *root, int level) {
if (root == nullptr) {
return;
}
@ -37,9 +36,8 @@ class Solution {
}
}
public:
vector<vector<int>> levelOrder(Node* root)
{
public:
vector<vector<int>> levelOrder(Node *root) {
vector<vector<int>> result;
levelOrder(result, root, 0);
return result;

View file

@ -21,8 +21,7 @@ public:
*/
class Solution {
void preorder(vector<int>& traversal, Node* root)
{
void preorder(vector<int> &traversal, Node *root) {
if (root == nullptr) {
return;
}
@ -33,9 +32,8 @@ class Solution {
}
}
public:
vector<int> preorder(Node* root)
{
public:
vector<int> preorder(Node *root) {
vector<int> result;
preorder(result, root);
return result;

View file

@ -3,13 +3,14 @@
#include <vector>
class Solution {
public:
int numberOfBeams(const std::vector<std::string>& bank) {
public:
int numberOfBeams(const std::vector<std::string> &bank) {
int beams = 0;
int last_row = 0;
for (const auto& row : bank) {
if (auto current_row = std::count(row.begin(), row.end(), '1'); current_row != 0) {
for (const auto &row : bank) {
if (auto current_row = std::count(row.begin(), row.end(), '1');
current_row != 0) {
beams += last_row * current_row;
last_row = current_row;
}
@ -18,4 +19,3 @@ public:
return beams;
}
};

View file

@ -1,6 +1,5 @@
class Solution {
bool matches(const string& s, const string& word) const
{
bool matches(const string &s, const string &word) const {
auto s_i = 0;
for (auto i = 0; s_i < s.size() && i < word.size(); i++) {
@ -12,23 +11,23 @@ class Solution {
return s_i == s.size();
}
map<string, int> preprocess(const vector<string>& words) const
{
map<string, int> preprocess(const vector<string> &words) const {
map<string, int> histogram;
for (auto& w : words) {
for (auto &w : words) {
histogram[w]++;
}
return histogram;
}
public:
int numMatchingSubseq(string s, vector<string>& words)
{
public:
int numMatchingSubseq(string s, vector<string> &words) {
auto histogram = preprocess(words);
return accumulate(histogram.begin(), histogram.end(), 0, [&](int acc, const auto& pair) {
return acc + (matches(pair.first, s) ? pair.second : 0);
});
return accumulate(histogram.begin(), histogram.end(), 0,
[&](int acc, const auto &pair) {
return acc +
(matches(pair.first, s) ? pair.second : 0);
});
}
};

View file

@ -2,8 +2,7 @@
namespace {
void nums_same_consec_diff(int n, int k, std::vector<int>& nums, int number)
{
void nums_same_consec_diff(int n, int k, std::vector<int> &nums, int number) {
if (n == 0) {
nums.push_back(number);
return;
@ -17,12 +16,11 @@ void nums_same_consec_diff(int n, int k, std::vector<int>& nums, int number)
}
}
}
} // namespace
class Solution {
public:
std::vector<int> numsSameConsecDiff(int n, int k)
{
public:
std::vector<int> numsSameConsecDiff(int n, int k) {
std::vector<int> nums;
for (int d = 1; d < 10; d++) {
@ -37,36 +35,32 @@ public:
#include <gtest/gtest.h>
TEST(examples, first)
{
TEST(examples, first) {
Solution s;
ASSERT_EQ(s.numsSameConsecDiff(3, 7), (std::vector { 181, 292, 707, 818, 929 }));
ASSERT_EQ(s.numsSameConsecDiff(3, 7),
(std::vector{181, 292, 707, 818, 929}));
}
TEST(examples, second)
{
TEST(examples, second) {
Solution s;
ASSERT_EQ(s.numsSameConsecDiff(2, 1),
(std::vector { 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78,
87, 89, 98 }));
(std::vector{10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76,
78, 87, 89, 98}));
}
TEST(same, two)
{
TEST(same, two) {
Solution s;
ASSERT_EQ(s.numsSameConsecDiff(2, 0),
(std::vector { 11, 22, 33, 44, 55, 66, 77, 88, 99 }));
(std::vector{11, 22, 33, 44, 55, 66, 77, 88, 99}));
}
TEST(same, three)
{
TEST(same, three) {
Solution s;
ASSERT_EQ(s.numsSameConsecDiff(3, 0),
(std::vector { 111, 222, 333, 444, 555, 666, 777, 888, 999 }));
(std::vector{111, 222, 333, 444, 555, 666, 777, 888, 999}));
}
int main(int argc, char** argv)
{
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View file

@ -1,5 +1,5 @@
class Solution {
private:
private:
const static unsigned CAP = 1000000007;
class dp {
@ -9,9 +9,7 @@ private:
std::vector<std::vector<std::map<int, unsigned>>> paths;
int
dfs(int y, int x, int moves)
{
int dfs(int y, int x, int moves) {
if (y < 0 || y >= rows || x < 0 || x >= cols) {
// BASE: we got out of the bounds
return 1;
@ -28,8 +26,8 @@ private:
}
int options = 0;
for (auto& [dx, dy] : std::vector<std::pair<int, int>> {
{ 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }) {
for (auto &[dx, dy] : std::vector<std::pair<int, int>>{
{0, 1}, {1, 0}, {0, -1}, {-1, 0}}) {
options = (options + dfs(y + dy, x + dx, moves - 1)) % CAP;
}
paths[y][x][moves] = options;
@ -37,26 +35,17 @@ private:
return options;
}
public:
public:
dp(int rows, int cols, int maxMove)
: rows(rows)
, cols(cols)
, maxMove(maxMove)
, paths(rows, std::vector<std::map<int, unsigned>>(cols))
{
}
: rows(rows), cols(cols), maxMove(maxMove),
paths(rows, std::vector<std::map<int, unsigned>>(cols)) {}
int
get(int row, int col)
{
return dfs(row, col, maxMove);
}
int get(int row, int col) { return dfs(row, col, maxMove); }
};
public:
int
findPaths(int m, int n, int maxMove, int startRow, int startColumn) const
{
public:
int findPaths(int m, int n, int maxMove, int startRow,
int startColumn) const {
return dp(m, n, maxMove).get(startRow, startColumn);
}
};

View file

@ -14,42 +14,24 @@
struct ListNode {
int val;
ListNode* next;
ListNode()
: val(0)
, next(nullptr)
{
}
ListNode(int x)
: val(x)
, next(nullptr)
{
}
ListNode(int x, ListNode* next)
: val(x)
, next(next)
{
}
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
namespace {
struct middle_t {
ListNode* node;
ListNode *node;
std::size_t size;
middle_t(ListNode* node, std::size_t size)
: node(node)
, size(size)
{
}
middle_t(ListNode *node, std::size_t size) : node(node), size(size) {}
};
middle_t
find_middle(ListNode* head)
{
ListNode* slow = head;
ListNode* fast = head->next;
middle_t find_middle(ListNode *head) {
ListNode *slow = head;
ListNode *fast = head->next;
std::size_t size;
for (size = 0; fast != nullptr && fast->next != nullptr; size++) {
@ -57,15 +39,15 @@ find_middle(ListNode* head)
fast = fast->next->next;
}
return { slow, size };
return {slow, size};
}
ListNode* reverse_list(ListNode* tail)
{
ListNode* previous = nullptr;
ListNode* next = nullptr;
ListNode *reverse_list(ListNode *tail) {
ListNode *previous = nullptr;
ListNode *next = nullptr;
for (ListNode* current = tail; current != nullptr; previous = current, current = next) {
for (ListNode *current = tail; current != nullptr;
previous = current, current = next) {
next = current->next;
current->next = previous;
}
@ -73,8 +55,7 @@ ListNode* reverse_list(ListNode* tail)
return previous;
}
bool compare_lists(ListNode* left, ListNode* right, std::size_t size)
{
bool compare_lists(ListNode *left, ListNode *right, std::size_t size) {
for (auto i = 0u; i < size + 1; i++) {
if (left->val != right->val) {
return false;
@ -89,9 +70,8 @@ bool compare_lists(ListNode* left, ListNode* right, std::size_t size)
} // namespace
class Solution {
public:
bool isPalindrome(ListNode* head)
{
public:
bool isPalindrome(ListNode *head) {
// find middle of the linked list
auto mid = find_middle(head);
@ -106,11 +86,9 @@ public:
#pragma region Testing utilities
namespace {
ListNode*
construct_list(const std::vector<int>& values)
{
ListNode* head = new ListNode(values.front());
ListNode* tail = head;
ListNode *construct_list(const std::vector<int> &values) {
ListNode *head = new ListNode(values.front());
ListNode *tail = head;
for (std::size_t i = 1; i < values.size(); i++) {
tail->next = new ListNode(values[i]);
@ -120,8 +98,7 @@ construct_list(const std::vector<int>& values)
return head;
}
void destroy_list(ListNode* linked_list)
{
void destroy_list(ListNode *linked_list) {
if (linked_list == nullptr) {
return;
}
@ -129,8 +106,7 @@ void destroy_list(ListNode* linked_list)
delete linked_list;
}
bool test_find_middle(const std::vector<int>& values, int mid_value)
{
bool test_find_middle(const std::vector<int> &values, int mid_value) {
auto linked_list = construct_list(values);
auto mid = find_middle(linked_list);
@ -140,8 +116,7 @@ bool test_find_middle(const std::vector<int>& values, int mid_value)
return result;
}
bool test_isPalindrome(const std::vector<int>& values)
{
bool test_isPalindrome(const std::vector<int> &values) {
auto linked_list = construct_list(values);
Solution s;
@ -154,19 +129,18 @@ bool test_isPalindrome(const std::vector<int>& values)
} // namespace
#pragma endregion // Testing utilities
int main()
{
int main() {
// find_middle tests
assert(test_find_middle(std::vector { 1, 2, 2, 1 }, 2));
assert(test_find_middle(std::vector { 1, 2, 3, 2, 1 }, 3));
assert(test_find_middle(std::vector { 1, 2 }, 1));
assert(test_find_middle(std::vector { 1 }, 1));
assert(test_find_middle(std::vector{1, 2, 2, 1}, 2));
assert(test_find_middle(std::vector{1, 2, 3, 2, 1}, 3));
assert(test_find_middle(std::vector{1, 2}, 1));
assert(test_find_middle(std::vector{1}, 1));
// isPalindrome tests
assert(test_isPalindrome(std::vector { 1, 2, 2, 1 }));
assert(test_isPalindrome(std::vector { 1, 2, 3, 2, 1 }));
assert(!test_isPalindrome(std::vector { 1, 2 }));
assert(test_isPalindrome(std::vector { 1 }));
assert(test_isPalindrome(std::vector{1, 2, 2, 1}));
assert(test_isPalindrome(std::vector{1, 2, 3, 2, 1}));
assert(!test_isPalindrome(std::vector{1, 2}));
assert(test_isPalindrome(std::vector{1}));
return 0;
}

View file

@ -9,22 +9,20 @@
* };
*/
class Solution {
ListNode* update_tail(ListNode* tail, ListNode* node) const
{
ListNode *update_tail(ListNode *tail, ListNode *node) const {
if (tail != nullptr) {
tail->next = node;
}
return node;
}
public:
ListNode* partition(ListNode* head, int x)
{
ListNode* left_head = nullptr;
ListNode* right_head = nullptr;
public:
ListNode *partition(ListNode *head, int x) {
ListNode *left_head = nullptr;
ListNode *right_head = nullptr;
ListNode* left_tail = nullptr;
ListNode* right_tail = nullptr;
ListNode *left_tail = nullptr;
ListNode *right_tail = nullptr;
while (head != nullptr) {
auto next_head = head->next;

View file

@ -1,13 +1,12 @@
class Solution {
public:
vector<int> getRow(int rowIndex)
{
public:
vector<int> getRow(int rowIndex) {
vector<int> result;
result.push_back(1);
for (auto k = 0; k < rowIndex; k++) {
auto next = static_cast<int>(
static_cast<long>(result.back()) * (rowIndex - k) / (k + 1));
auto next = static_cast<int>(static_cast<long>(result.back()) *
(rowIndex - k) / (k + 1));
result.push_back(next);
}

View file

@ -1,22 +1,20 @@
class Solution {
int getN(const vector<int>& previousRow, int n)
{
int getN(const vector<int> &previousRow, int n) {
if (n == 0 || n == previousRow.size()) {
return 1;
}
return previousRow[n - 1] + previousRow[n];
}
public:
vector<vector<int>> generate(int numRows)
{
public:
vector<vector<int>> generate(int numRows) {
if (numRows <= 0) {
return {};
}
vector<vector<int>> result { vector<int> { 1 } };
vector<vector<int>> result{vector<int>{1}};
for (auto i = 2; i <= numRows; i++) {
auto& previous = result.back();
auto &previous = result.back();
vector<int> current;
for (auto j = 0; j < i; j++) {

View file

@ -4,8 +4,7 @@
namespace {
std::map<char, int> build_freqs(const std::string& input)
{
std::map<char, int> build_freqs(const std::string &input) {
std::map<char, int> freqs;
for (auto c : input) {
@ -15,8 +14,7 @@ std::map<char, int> build_freqs(const std::string& input)
return freqs;
}
bool subtract(std::map<char, int> available, const std::string& message)
{
bool subtract(std::map<char, int> available, const std::string &message) {
for (auto c : message) {
available[c]--;
@ -28,19 +26,18 @@ bool subtract(std::map<char, int> available, const std::string& message)
return true;
}
}
} // namespace
class Solution {
public:
bool canConstruct(const std::string& ransomNote, const std::string& magazine)
{
public:
bool canConstruct(const std::string &ransomNote,
const std::string &magazine) {
auto available = build_freqs(magazine);
return subtract(available, ransomNote);
}
};
int main()
{
int main() {
Solution s;
assert(!s.canConstruct("a", "b"));

View file

@ -2,9 +2,8 @@
#include <vector>
class Solution {
public:
std::string removeStars(const std::string& s)
{
public:
std::string removeStars(const std::string &s) {
std::vector<char> without_stars;
for (auto c : s) {
@ -15,6 +14,6 @@ public:
}
}
return std::string { without_stars.begin(), without_stars.end() };
return std::string{without_stars.begin(), without_stars.end()};
}
};

View file

@ -4,10 +4,7 @@
namespace {
bool is_power_of_2(int n)
{
return (n & (n - 1)) == 0;
}
bool is_power_of_2(int n) { return (n & (n - 1)) == 0; }
class permutations {
using values_t = typename std::vector<char>;
@ -16,46 +13,38 @@ class permutations {
values_t elements;
bool last;
public:
public:
p_iter(values_t elements, bool last = false)
: elements(elements)
, last(last)
{
}
: elements(elements), last(last) {}
const values_t& operator*() const { return elements; }
const values_t &operator*() const { return elements; }
p_iter& operator++()
{
p_iter &operator++() {
if (!std::next_permutation(elements.begin(), elements.end())) {
last = true;
}
return *this;
}
bool operator==(const p_iter& other) const
{
bool operator==(const p_iter &other) const {
return last == other.last && elements == other.elements;
}
bool operator!=(const p_iter& other) const { return !(*this == other); }
bool operator!=(const p_iter &other) const { return !(*this == other); }
};
values_t elements;
public:
permutations(const values_t& input_ints)
: elements(input_ints)
{
public:
permutations(const values_t &input_ints) : elements(input_ints) {
std::sort(elements.begin(), elements.end());
}
p_iter begin() const { return { elements, elements.empty() }; }
p_iter end() const { return { elements, true }; }
p_iter begin() const { return {elements, elements.empty()}; }
p_iter end() const { return {elements, true}; }
};
std::vector<char> to_vector(int n)
{
std::vector<char> to_vector(int n) {
if (n == 0) {
return std::vector<char>(1, 0);
}
@ -70,8 +59,7 @@ std::vector<char> to_vector(int n)
return digits;
}
int to_number(const std::vector<char> digits)
{
int to_number(const std::vector<char> digits) {
int number = 0;
for (auto digit : digits) {
@ -81,13 +69,12 @@ int to_number(const std::vector<char> digits)
return number;
}
}
} // namespace
class Solution {
public:
bool reorderedPowerOf2(int n)
{
for (const auto& permutation : permutations(to_vector(n))) {
public:
bool reorderedPowerOf2(int n) {
for (const auto &permutation : permutations(to_vector(n))) {
if (permutation.front() == 0) {
continue;
}
@ -101,8 +88,7 @@ public:
}
};
int main()
{
int main() {
Solution s;
assert(s.reorderedPowerOf2(1));

View file

@ -2,16 +2,15 @@
#include <vector>
class Solution {
public:
void rotate(std::vector<std::vector<int>>& matrix)
{
public:
void rotate(std::vector<std::vector<int>> &matrix) {
for (std::size_t i = 0; i < matrix.size(); i++) {
for (std::size_t j = i; j < matrix.size(); j++) {
std::swap(matrix[i][j], matrix[j][i]);
}
}
for (auto& row : matrix) {
for (auto &row : matrix) {
std::reverse(row.begin(), row.end());
}
}

View file

@ -6,13 +6,13 @@
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q)
{
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if (p == nullptr && q == nullptr) {
return true;
}

View file

@ -7,24 +7,14 @@ class SnapshotArray {
int snap_id = 0;
std::vector<std::map<int, int>> arr;
public:
SnapshotArray(int length)
: arr(length, std::map<int, int> { { 0, 0 } })
{
}
public:
SnapshotArray(int length) : arr(length, std::map<int, int>{{0, 0}}) {}
void set(int index, int val)
{
arr[index][snap_id] = val;
}
void set(int index, int val) { arr[index][snap_id] = val; }
int snap()
{
return snap_id++;
}
int snap() { return snap_id++; }
int get(int index, int snap_id)
{
int get(int index, int snap_id) {
auto it = std::prev(arr[index].lower_bound(snap_id + 1));
return it == arr[index].end() ? 0 : it->second;
}
@ -38,8 +28,7 @@ public:
* int param_3 = obj->get(index,snap_id);
*/
int main()
{
int main() {
SnapshotArray arr(3);
arr.set(0, 5);
assert(arr.snap() == 0);

View file

@ -7,10 +7,8 @@
namespace {
template <typename T>
void print_matrix(const std::vector<std::vector<T>>& m)
{
for (const auto& row : m) {
template <typename T> void print_matrix(const std::vector<std::vector<T>> &m) {
for (const auto &row : m) {
for (auto x : row) {
std::cout << x << " ";
}
@ -21,48 +19,41 @@ void print_matrix(const std::vector<std::vector<T>>& m)
std::cout << "\n";
}
template <typename T>
class diagonal {
std::vector<std::vector<T>>& matrix;
template <typename T> class diagonal {
std::vector<std::vector<T>> &matrix;
std::size_t x;
std::size_t y;
class diagonal_iter {
std::vector<std::vector<T>>& m;
std::vector<std::vector<T>> &m;
std::size_t x;
std::size_t y;
public:
public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using pointer = T *;
using reference = T &;
using iterator_category = std::random_access_iterator_tag;
diagonal_iter(std::vector<std::vector<T>>& matrix,
std::size_t x,
std::size_t y)
: m(matrix)
, x(x)
, y(y)
{
}
diagonal_iter(std::vector<std::vector<T>> &matrix, std::size_t x,
std::size_t y)
: m(matrix), x(x), y(y) {}
bool operator!=(const diagonal_iter& rhs) const
{
bool operator!=(const diagonal_iter &rhs) const {
return m != rhs.m || x != rhs.x || y != rhs.y;
}
bool operator==(const diagonal_iter& rhs) const { return !(*this != rhs); }
bool operator==(const diagonal_iter &rhs) const {
return !(*this != rhs);
}
diagonal_iter& operator++()
{
diagonal_iter &operator++() {
x++;
y++;
return *this;
}
diagonal_iter operator--()
{
diagonal_iter operator--() {
x--;
y--;
return *this;
@ -70,21 +61,18 @@ class diagonal {
reference operator*() const { return m[y][x]; }
diagonal_iter operator-(difference_type n) const
{
return diagonal_iter { m, x - n, y - n };
diagonal_iter operator-(difference_type n) const {
return diagonal_iter{m, x - n, y - n};
}
int operator-(const diagonal_iter& rhs) const { return x - rhs.x; }
int operator-(const diagonal_iter &rhs) const { return x - rhs.x; }
diagonal_iter operator+(difference_type n) const
{
return diagonal_iter { m, x + n, y + n };
diagonal_iter operator+(difference_type n) const {
return diagonal_iter{m, x + n, y + n};
}
bool operator<(const diagonal_iter& rhs) const { return x < rhs.x; }
bool operator<(const diagonal_iter &rhs) const { return x < rhs.x; }
diagonal_iter& operator=(const diagonal_iter& rhs)
{
diagonal_iter &operator=(const diagonal_iter &rhs) {
if (this != &rhs) // not a self-assignment
{
this->m = rhs.m;
@ -95,53 +83,40 @@ class diagonal {
}
};
public:
diagonal(std::vector<std::vector<T>>& matrix, std::size_t x, std::size_t y)
: matrix(matrix)
, x(x)
, y(y)
{
}
public:
diagonal(std::vector<std::vector<T>> &matrix, std::size_t x, std::size_t y)
: matrix(matrix), x(x), y(y) {}
diagonal_iter begin() const { return diagonal_iter { matrix, x, y }; }
diagonal_iter begin() const { return diagonal_iter{matrix, x, y}; }
diagonal_iter end() const
{
diagonal_iter end() const {
auto max_x = matrix[y].size();
auto max_y = matrix.size();
auto steps = std::min(max_x - x, max_y - y);
return diagonal_iter { matrix, x + steps, y + steps };
return diagonal_iter{matrix, x + steps, y + steps};
}
};
template <typename T>
class diagonals {
std::vector<std::vector<T>>& _matrix;
template <typename T> class diagonals {
std::vector<std::vector<T>> &_matrix;
class diagonals_iter {
std::vector<std::vector<T>>& m;
std::vector<std::vector<T>> &m;
std::size_t x;
std::size_t y;
public:
diagonals_iter(std::vector<std::vector<T>>& matrix,
std::size_t x,
std::size_t y)
: m(matrix)
, x(x)
, y(y)
{
}
public:
diagonals_iter(std::vector<std::vector<T>> &matrix, std::size_t x,
std::size_t y)
: m(matrix), x(x), y(y) {}
bool operator!=(const diagonals_iter& rhs) const
{
bool operator!=(const diagonals_iter &rhs) const {
return m != rhs.m || x != rhs.x || y != rhs.y;
}
diagonals_iter& operator++()
{
diagonals_iter &operator++() {
if (y != 0) {
// iterating through diagonals down the first column
y++;
@ -159,24 +134,21 @@ class diagonals {
return *this;
}
diagonal<T> operator*() const { return diagonal { m, x, y }; }
diagonal<T> operator*() const { return diagonal{m, x, y}; }
};
public:
diagonals(std::vector<std::vector<T>>& matrix)
: _matrix(matrix)
{
}
diagonals_iter begin() { return diagonals_iter { _matrix, 0, 0 }; }
diagonals_iter end() { return diagonals_iter { _matrix, 0, _matrix.size() }; }
public:
diagonals(std::vector<std::vector<T>> &matrix) : _matrix(matrix) {}
diagonals_iter begin() { return diagonals_iter{_matrix, 0, 0}; }
diagonals_iter end() { return diagonals_iter{_matrix, 0, _matrix.size()}; }
};
} // namespace
class Solution {
public:
std::vector<std::vector<int>> diagonalSort(std::vector<std::vector<int>> mat)
{
public:
std::vector<std::vector<int>>
diagonalSort(std::vector<std::vector<int>> mat) {
for (auto d : diagonals(mat)) {
std::sort(d.begin(), d.end());
}
@ -185,44 +157,38 @@ public:
}
};
static void
test_case_1()
{
static void test_case_1() {
// Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
// Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
Solution s;
assert((s.diagonalSort(std::vector { std::vector { 3, 3, 1, 1 },
std::vector { 2, 2, 1, 2 },
std::vector { 1, 1, 1, 2 } })
== std::vector { std::vector { 1, 1, 1, 1 },
std::vector { 1, 2, 2, 2 },
std::vector { 1, 2, 3, 3 } }));
assert((s.diagonalSort(std::vector{std::vector{3, 3, 1, 1},
std::vector{2, 2, 1, 2},
std::vector{1, 1, 1, 2}}) ==
std::vector{std::vector{1, 1, 1, 1}, std::vector{1, 2, 2, 2},
std::vector{1, 2, 3, 3}}));
}
static void
test_case_2()
{
static void test_case_2() {
// Input: mat =
// [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]
// Output:
// [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]
Solution s;
assert((s.diagonalSort(std::vector { std::vector { 11, 25, 66, 1, 69, 7 },
std::vector { 23, 55, 17, 45, 15, 52 },
std::vector { 75, 31, 36, 44, 58, 8 },
std::vector { 22, 27, 33, 25, 68, 4 },
std::vector { 84, 28, 14, 11, 5, 50 } })
== std::vector { std::vector { 5, 17, 4, 1, 52, 7 },
std::vector { 11, 11, 25, 45, 8, 69 },
std::vector { 14, 23, 25, 44, 58, 15 },
std::vector { 22, 27, 31, 36, 50, 66 },
std::vector { 84, 28, 75, 33, 55, 68 } }));
assert((s.diagonalSort(std::vector{std::vector{11, 25, 66, 1, 69, 7},
std::vector{23, 55, 17, 45, 15, 52},
std::vector{75, 31, 36, 44, 58, 8},
std::vector{22, 27, 33, 25, 68, 4},
std::vector{84, 28, 14, 11, 5, 50}}) ==
std::vector{std::vector{5, 17, 4, 1, 52, 7},
std::vector{11, 11, 25, 45, 8, 69},
std::vector{14, 23, 25, 44, 58, 15},
std::vector{22, 27, 31, 36, 50, 66},
std::vector{84, 28, 75, 33, 55, 68}}));
}
int main()
{
int main() {
test_case_1();
test_case_2();

View file

@ -3,100 +3,103 @@
#include <vector>
class Solution {
struct indices {
int x;
int y;
struct indices {
int x;
int y;
bool operator==(const indices& other) const = default;
indices& operator+=(const indices& other) {
x += other.x;
y += other.y;
return *this;
}
friend indices operator+(indices left, const indices& right) {
return left += right;
}
int& operator[](std::vector<std::vector<int>>& mat) const {
return mat[y][x];
}
};
struct spiral_indices {
spiral_indices(const std::vector<std::vector<int>>& matrix)
: x_bounds{-1, static_cast<int>(matrix.size() ? matrix[0].size() : 0)},
y_bounds{-1, static_cast<int>(matrix.size())} {}
bool done() const { return !in_bounds(idx); }
spiral_indices& operator++() {
// update bounds and change the direction if cannot move
if (!in_bounds(idx + d)) {
// change the direction
d = {-d.y, d.x};
// get the magnitude of the vector
auto flat_d = d.x + d.y;
// decide whether we're moving x or y bounds
auto& bounds = d.x ? x_bounds : y_bounds;
if (flat_d > 0) {
bounds.x++;
} else {
bounds.y--;
bool operator==(const indices &other) const = default;
indices &operator+=(const indices &other) {
x += other.x;
y += other.y;
return *this;
}
}
idx += d;
friend indices operator+(indices left, const indices &right) {
return left += right;
}
return *this;
int &operator[](std::vector<std::vector<int>> &mat) const {
return mat[y][x];
}
};
struct spiral_indices {
spiral_indices(const std::vector<std::vector<int>> &matrix)
: x_bounds{-1,
static_cast<int>(matrix.size() ? matrix[0].size() : 0)},
y_bounds{-1, static_cast<int>(matrix.size())} {}
bool done() const { return !in_bounds(idx); }
spiral_indices &operator++() {
// update bounds and change the direction if cannot move
if (!in_bounds(idx + d)) {
// change the direction
d = {-d.y, d.x};
// get the magnitude of the vector
auto flat_d = d.x + d.y;
// decide whether we're moving x or y bounds
auto &bounds = d.x ? x_bounds : y_bounds;
if (flat_d > 0) {
bounds.x++;
} else {
bounds.y--;
}
}
idx += d;
return *this;
}
int &operator[](std::vector<std::vector<int>> &mat) const {
return idx[mat];
}
private:
indices idx{0, 0};
indices d{1, 0};
indices x_bounds, y_bounds;
bool in_bounds(const indices &idx) const {
return (x_bounds.x < idx.x && idx.x < x_bounds.y) &&
(y_bounds.x < idx.y && idx.y < y_bounds.y);
}
};
public:
std::vector<std::vector<int>> generateMatrix(int n) {
auto length = static_cast<std::size_t>(n);
std::vector<std::vector<int>> spiral{length,
std::vector<int>(length, 0)};
int i = 1;
for (spiral_indices idx{spiral}; !idx.done(); ++idx) {
idx[spiral] = i++;
}
return spiral;
}
int& operator[](std::vector<std::vector<int>>& mat) const {
return idx[mat];
}
private:
indices idx{0, 0};
indices d{1, 0};
indices x_bounds, y_bounds;
bool in_bounds(const indices& idx) const {
return (x_bounds.x < idx.x && idx.x < x_bounds.y) &&
(y_bounds.x < idx.y && idx.y < y_bounds.y);
}
};
public:
std::vector<std::vector<int>> generateMatrix(int n) {
auto length = static_cast<std::size_t>(n);
std::vector<std::vector<int>> spiral{length, std::vector<int>(length, 0)};
int i = 1;
for (spiral_indices idx{spiral}; !idx.done(); ++idx) {
idx[spiral] = i++;
}
return spiral;
}
};
int main() {
Solution s;
Solution s;
assert((s.generateMatrix(0) == std::vector<std::vector<int>>{}));
assert((s.generateMatrix(1) == std::vector<std::vector<int>>{{1}}));
assert(
(s.generateMatrix(2) == std::vector<std::vector<int>>{{1, 2}, {4, 3}}));
assert((s.generateMatrix(0) == std::vector<std::vector<int>>{}));
assert((s.generateMatrix(1) == std::vector<std::vector<int>>{{1}}));
assert(
(s.generateMatrix(2) == std::vector<std::vector<int>>{{1, 2}, {4, 3}}));
for (auto&& row : s.generateMatrix(3)) {
for (auto x : row) std::cout << x << " ";
std::cout << "\n";
}
for (auto &&row : s.generateMatrix(3)) {
for (auto x : row)
std::cout << x << " ";
std::cout << "\n";
}
assert((s.generateMatrix(3) ==
std::vector<std::vector<int>>{{1, 2, 3}, {8, 9, 4}, {7, 6, 5}}));
assert((s.generateMatrix(3) ==
std::vector<std::vector<int>>{{1, 2, 3}, {8, 9, 4}, {7, 6, 5}}));
return 0;
return 0;
}

View file

@ -2,90 +2,90 @@
#include <vector>
class Solution {
struct indices {
int x;
int y;
struct indices {
int x;
int y;
bool operator==(const indices& other) const = default;
indices& operator+=(const indices& other) {
x += other.x;
y += other.y;
return *this;
}
friend indices operator+(indices left, const indices& right) {
return left += right;
}
int operator[](const std::vector<std::vector<int>>& mat) const {
return mat[y][x];
}
};
struct spiral_indices {
spiral_indices(const std::vector<std::vector<int>>& matrix)
: x_bounds{-1, static_cast<int>(matrix[0].size())},
y_bounds{-1, static_cast<int>(matrix.size())} {}
bool done() const { return !in_bounds(idx); }
spiral_indices& operator++() {
// update bounds and change the direction if cannot move
if (!in_bounds(idx + d)) {
// change the direction
d = {-d.y, d.x};
// get the magnitude of the vector
auto flat_d = d.x + d.y;
// decide whether we're moving x or y bounds
auto& bounds = d.x ? x_bounds : y_bounds;
if (flat_d > 0) {
bounds.x++;
} else {
bounds.y--;
bool operator==(const indices &other) const = default;
indices &operator+=(const indices &other) {
x += other.x;
y += other.y;
return *this;
}
}
idx += d;
friend indices operator+(indices left, const indices &right) {
return left += right;
}
return *this;
int operator[](const std::vector<std::vector<int>> &mat) const {
return mat[y][x];
}
};
struct spiral_indices {
spiral_indices(const std::vector<std::vector<int>> &matrix)
: x_bounds{-1, static_cast<int>(matrix[0].size())},
y_bounds{-1, static_cast<int>(matrix.size())} {}
bool done() const { return !in_bounds(idx); }
spiral_indices &operator++() {
// update bounds and change the direction if cannot move
if (!in_bounds(idx + d)) {
// change the direction
d = {-d.y, d.x};
// get the magnitude of the vector
auto flat_d = d.x + d.y;
// decide whether we're moving x or y bounds
auto &bounds = d.x ? x_bounds : y_bounds;
if (flat_d > 0) {
bounds.x++;
} else {
bounds.y--;
}
}
idx += d;
return *this;
}
int operator[](const std::vector<std::vector<int>> &mat) const {
return idx[mat];
}
private:
indices idx{0, 0};
indices d{1, 0};
indices x_bounds, y_bounds;
bool in_bounds(const indices &idx) const {
return (x_bounds.x < idx.x && idx.x < x_bounds.y) &&
(y_bounds.x < idx.y && idx.y < y_bounds.y);
}
};
public:
std::vector<int> spiralOrder(const std::vector<std::vector<int>> &matrix) {
std::vector<int> spiral;
for (spiral_indices idx{matrix}; !idx.done(); ++idx) {
spiral.push_back(idx[matrix]);
}
return spiral;
}
int operator[](const std::vector<std::vector<int>>& mat) const {
return idx[mat];
}
private:
indices idx{0, 0};
indices d{1, 0};
indices x_bounds, y_bounds;
bool in_bounds(const indices& idx) const {
return (x_bounds.x < idx.x && idx.x < x_bounds.y) &&
(y_bounds.x < idx.y && idx.y < y_bounds.y);
}
};
public:
std::vector<int> spiralOrder(const std::vector<std::vector<int>>& matrix) {
std::vector<int> spiral;
for (spiral_indices idx{matrix}; !idx.done(); ++idx) {
spiral.push_back(idx[matrix]);
}
return spiral;
}
};
int main() {
Solution s;
Solution s;
assert((s.spiralOrder({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}) ==
std::vector{1, 2, 3, 6, 9, 8, 7, 4, 5}));
assert((s.spiralOrder({{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}) ==
std::vector{1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7}));
assert((s.spiralOrder({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}) ==
std::vector{1, 2, 3, 6, 9, 8, 7, 4, 5}));
assert((s.spiralOrder({{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}) ==
std::vector{1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7}));
return 0;
return 0;
}

View file

@ -4,8 +4,8 @@
#include <vector>
class Solution {
public:
std::vector<int> getSumAbsoluteDifferences(const std::vector<int>& nums) {
public:
std::vector<int> getSumAbsoluteDifferences(const std::vector<int> &nums) {
auto total = std::accumulate(nums.begin(), nums.end(), 0);
auto left = 0;

View file

@ -1,15 +1,13 @@
class Solution {
int right(const std::vector<int>& row, int size, int idx) const
{
int right(const std::vector<int> &row, int size, int idx) const {
if (idx >= size) {
return 0;
}
return row[idx];
}
public:
int uniquePaths(int m, int n)
{
public:
int uniquePaths(int m, int n) {
std::vector<int> bottom(n, 1);
for (int y = m - 2; y >= 0; y--) {

View file

@ -10,27 +10,16 @@ namespace {
class todo : public std::exception {
std::string cause;
public:
todo()
: cause("Not yet implemented!")
{
}
public:
todo() : cause("Not yet implemented!") {}
todo(std::string&& excuse)
: cause("Not yet implemented: " + excuse)
{
}
todo(std::string &&excuse) : cause("Not yet implemented: " + excuse) {}
virtual const char* what() const throw()
{
return cause.c_str();
}
virtual const char *what() const throw() { return cause.c_str(); }
};
auto expected_size(int first) -> std::optional<std::size_t> {
static constexpr std::array<int, 4> HEADERS = {
0, 6, 14, 30
};
static constexpr std::array<int, 4> HEADERS = {0, 6, 14, 30};
for (auto i = 0; i < 4; i++) {
auto mask_length = 1 + i + (i > 0);
@ -44,14 +33,13 @@ auto expected_size(int first) -> std::optional<std::size_t> {
return {};
}
}
} // namespace
class Solution {
static constexpr int CONTINUATION_BYTE = 2;
public:
auto validUtf8(const std::vector<int>& data) -> bool
{
public:
auto validUtf8(const std::vector<int> &data) -> bool {
for (auto i = 0; i < data.size();) {
auto expected_length = expected_size(data[i]);
if (!expected_length.has_value()) {
@ -60,7 +48,8 @@ public:
}
if (i + *expected_length > data.size()) {
// std::cout << "unexpected length of size " << data.size() << " ≠ " << *expected_length << "\n";
// std::cout << "unexpected length of size " << data.size() << "
// ≠ " << *expected_length << "\n";
return false;
}
@ -89,31 +78,27 @@ public:
#include <gtest/gtest.h>
TEST(examples, valid)
{
TEST(examples, valid) {
Solution s;
ASSERT_TRUE(s.validUtf8(std::vector { 197, 130, 1 }));
ASSERT_TRUE(s.validUtf8(std::vector{197, 130, 1}));
}
TEST(examples, invalid)
{
TEST(examples, invalid) {
Solution s;
ASSERT_FALSE(s.validUtf8(std::vector { 235, 140, 4 }));
ASSERT_FALSE(s.validUtf8(std::vector{235, 140, 4}));
}
TEST(valid, ascii_byte)
{
TEST(valid, ascii_byte) {
Solution s;
ASSERT_TRUE(s.validUtf8(std::vector { 64 }));
ASSERT_TRUE(s.validUtf8(std::vector{64}));
}
TEST(invalid, just_one_byte) {
Solution s;
ASSERT_FALSE(s.validUtf8(std::vector {2 << 7}));
ASSERT_FALSE(s.validUtf8(std::vector{2 << 7}));
}
int main(int argc, char** argv)
{
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View file

@ -3,8 +3,8 @@
#include <string>
class Solution {
public:
bool isAnagram(const std::string& s, const std::string& t) {
public:
bool isAnagram(const std::string &s, const std::string &t) {
std::array<int, 26> counter{};
for (char c : s) {
@ -19,8 +19,7 @@ public:
}
}
return std::all_of(counter.begin(), counter.end(), [](auto c) {
return c == 0;
});
return std::all_of(counter.begin(), counter.end(),
[](auto c) { return c == 0; });
}
};

View file

@ -2,9 +2,8 @@
#include <vector>
class Solution {
public:
bool isValid(const std::string& s)
{
public:
bool isValid(const std::string &s) {
std::vector<char> st;
for (auto c : s) {

View file

@ -5,54 +5,30 @@
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode()
: val(0)
, left(nullptr)
, right(nullptr)
{
}
TreeNode(int x)
: val(x)
, left(nullptr)
, right(nullptr)
{
}
TreeNode(int x, TreeNode* left, TreeNode* right)
: val(x)
, left(left)
, right(right)
{
}
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right)
: val(x), left(left), right(right) {}
};
namespace {
struct TreeNodeHandle {
TreeNode* node;
TreeNode *node;
int x;
int y;
TreeNodeHandle(TreeNode* node, int x, int y)
: node(node)
, x(x)
, y(y)
{
}
TreeNodeHandle(TreeNode *node, int x, int y) : node(node), x(x), y(y) {}
bool operator==(const TreeNodeHandle& rhs) const
{
bool operator==(const TreeNodeHandle &rhs) const {
return node == rhs.node && x == rhs.x && y == rhs.y;
}
int value() const
{
return node->val;
}
int value() const { return node->val; }
bool operator<(const TreeNodeHandle& rhs) const
{
bool operator<(const TreeNodeHandle &rhs) const {
if (y != rhs.y) {
return y < rhs.y;
}
@ -66,75 +42,62 @@ struct TreeNodeHandle {
};
class verticals {
TreeNode* root;
TreeNode *root;
class verticals_iter {
std::deque<TreeNodeHandle> queue;
void advance()
{
auto& n = queue.front();
void advance() {
auto &n = queue.front();
if (n.node->left != nullptr) {
queue.push_back(TreeNodeHandle(n.node->left, n.x - 1, n.y + 1));
}
if (n.node->right != nullptr) {
queue.push_back(TreeNodeHandle(n.node->right, n.x + 1, n.y + 1));
queue.push_back(
TreeNodeHandle(n.node->right, n.x + 1, n.y + 1));
}
}
public:
verticals_iter(std::deque<TreeNodeHandle> queue)
: queue(queue)
{
public:
verticals_iter(std::deque<TreeNodeHandle> queue) : queue(queue) {
if (queue.front().node == nullptr) {
queue.pop_front();
}
}
bool operator!=(const verticals_iter& other) const
{
bool operator!=(const verticals_iter &other) const {
return queue != other.queue;
}
verticals_iter operator++()
{
verticals_iter operator++() {
advance();
queue.pop_front();
return *this;
}
TreeNodeHandle& operator*()
{
return queue.front();
}
TreeNodeHandle &operator*() { return queue.front(); }
};
public:
verticals(TreeNode* root)
: root(root)
{
public:
verticals(TreeNode *root) : root(root) {}
verticals_iter begin() const {
return verticals_iter(std::deque{TreeNodeHandle(root, 0, 0)});
}
verticals_iter begin() const
{
return verticals_iter(std::deque { TreeNodeHandle(root, 0, 0) });
}
verticals_iter end() const
{
verticals_iter end() const {
std::deque<TreeNodeHandle> q;
return verticals_iter(q);
}
};
}
} // namespace
class Solution {
public:
std::vector<std::vector<int>> verticalTraversal(TreeNode* root)
{
public:
std::vector<std::vector<int>> verticalTraversal(TreeNode *root) {
std::map<int, std::vector<TreeNodeHandle>> traversals;
int min_x = 0;
@ -150,13 +113,13 @@ public:
std::vector<std::vector<int>> result;
for (int x = min_x; x <= max_x; x++) {
auto& v = traversals[x];
auto &v = traversals[x];
if (v.size()) {
std::sort(v.begin(), v.end());
result.push_back(std::vector<int> {});
result.push_back(std::vector<int>{});
for (auto& n : v) {
for (auto &n : v) {
result.back().push_back(n.value());
}
}
@ -172,8 +135,7 @@ public:
namespace _tests {
TreeNode* construct_tree(const std::vector<int>& values, std::size_t i = 0)
{
TreeNode *construct_tree(const std::vector<int> &values, std::size_t i = 0) {
if (i >= values.size() || values[i] == -1) {
return nullptr;
}
@ -185,8 +147,7 @@ TreeNode* construct_tree(const std::vector<int>& values, std::size_t i = 0)
return tree;
}
void destruct_tree(TreeNode* ptr)
{
void destruct_tree(TreeNode *ptr) {
if (ptr == nullptr) {
return;
}
@ -196,46 +157,49 @@ void destruct_tree(TreeNode* ptr)
delete ptr;
}
}
} // namespace _tests
TEST(examples, first)
{
TEST(examples, first) {
Solution s;
auto t = _tests::construct_tree(std::vector { 3, 9, 20, -1, -1, 15, 7 });
EXPECT_EQ(s.verticalTraversal(t), (std::vector { std::vector { 9 }, std::vector { 3, 15 }, std::vector { 20 }, std::vector { 7 } }));
auto t = _tests::construct_tree(std::vector{3, 9, 20, -1, -1, 15, 7});
EXPECT_EQ(s.verticalTraversal(t),
(std::vector{std::vector{9}, std::vector{3, 15}, std::vector{20},
std::vector{7}}));
_tests::destruct_tree(t);
}
TEST(examples, second)
{
TEST(examples, second) {
Solution s;
auto t = _tests::construct_tree(std::vector { 1, 2, 3, 4, 5, 6, 7 });
EXPECT_EQ(s.verticalTraversal(t), (std::vector { std::vector { 4 }, std::vector { 2 }, std::vector { 1, 5, 6 }, std::vector { 3 }, std::vector { 7 } }));
auto t = _tests::construct_tree(std::vector{1, 2, 3, 4, 5, 6, 7});
EXPECT_EQ(s.verticalTraversal(t),
(std::vector{std::vector{4}, std::vector{2}, std::vector{1, 5, 6},
std::vector{3}, std::vector{7}}));
_tests::destruct_tree(t);
}
TEST(examples, third)
{
TEST(examples, third) {
Solution s;
auto t = _tests::construct_tree(std::vector { 1, 2, 3, 4, 6, 5, 7 });
EXPECT_EQ(s.verticalTraversal(t), (std::vector { std::vector { 4 }, std::vector { 2 }, std::vector { 1, 5, 6 }, std::vector { 3 }, std::vector { 7 } }));
auto t = _tests::construct_tree(std::vector{1, 2, 3, 4, 6, 5, 7});
EXPECT_EQ(s.verticalTraversal(t),
(std::vector{std::vector{4}, std::vector{2}, std::vector{1, 5, 6},
std::vector{3}, std::vector{7}}));
_tests::destruct_tree(t);
}
TEST(submission, first)
{
TEST(submission, first) {
Solution s;
auto t = _tests::construct_tree(std::vector { 3, 1, 4, 0, 2, 2 });
EXPECT_EQ(s.verticalTraversal(t), (std::vector { std::vector { 0 }, std::vector { 1 }, std::vector { 3, 2, 2 }, std::vector { 4 } }));
auto t = _tests::construct_tree(std::vector{3, 1, 4, 0, 2, 2});
EXPECT_EQ(s.verticalTraversal(t),
(std::vector{std::vector{0}, std::vector{1}, std::vector{3, 2, 2},
std::vector{4}}));
_tests::destruct_tree(t);
}
int main(int argc, char** argv)
{
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View file

@ -2,10 +2,10 @@
#include <set>
class Solution {
public:
int maxWidthOfVerticalArea(const std::vector<std::vector<int>>& points) {
public:
int maxWidthOfVerticalArea(const std::vector<std::vector<int>> &points) {
std::set<int> seen;
for (const auto& point : points) {
for (const auto &point : points) {
seen.insert(point[0]);
}