commit 422ba403df8ba4705f5f18e3f910fb4035c2409c
parent 98caf468181173e545668a85e597fccfe207b532
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date: Sat, 26 Aug 2023 12:23:11 +0200
Improve .clang-format, and reformat
Diffstat:
660 files changed, 12063 insertions(+), 12028 deletions(-)
diff --git a/.clang-format b/.clang-format
@@ -1,26 +1,45 @@
---
Language: Cpp
-# BasedOnStyle: LLVM
+# BasedOnStyle: Microsoft
AccessModifierOffset: -2
-AlignAfterOpenBracket: true
-AlignArrayOfStructures: Right
-AlignConsecutiveMacros: true
-AlignConsecutiveAssignments: None
-AlignConsecutiveBitFields: None
-AlignConsecutiveDeclarations: None
+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
AlignEscapedNewlines: Right
AlignOperands: Align
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
-AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
-AllowShortEnumsOnASingleLine: true
-AllowShortBlocksOnASingleLine: true
+AllowShortEnumsOnASingleLine: false
+AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: true
-AllowShortFunctionsOnASingleLine: All
+AllowShortFunctionsOnASingleLine: true
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: true
-AllowShortLoopsOnASingleLine: true
+AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
@@ -32,7 +51,7 @@ BinPackParameters: true
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
- AfterControlStatement: Never
+ AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
@@ -49,8 +68,8 @@ BraceWrapping:
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
-BreakBeforeConceptDeclarations: true
-BreakBeforeBraces: Attach
+BreakBeforeConceptDeclarations: Always
+BreakBeforeBraces: Custom
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
@@ -58,10 +77,10 @@ BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
-ColumnLimit: 80
+ColumnLimit: 110
CommentPragmas: '^ IWYU pragma:'
+QualifierAlignment: Leave
CompactNamespaces: false
-ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
@@ -71,6 +90,10 @@ DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: false
+PackConstructorInitializers: BinPack
+BasedOnStyle: ''
+ConstructorInitializerAllOnOneLineOrOnePerLine: false
+AllowAllConstructorInitializersOnNextLine: true
FixNamespaceComments: true
ForEachMacros:
- foreach
@@ -100,9 +123,10 @@ IndentCaseBlocks: false
IndentGotoLabels: true
IndentPPDirectives: None
IndentExternBlock: AfterExternBlock
-IndentRequires: false
-IndentWidth: 2
+IndentRequiresClause: true
+IndentWidth: 4
IndentWrappedFunctionNames: false
+InsertBraces: false
InsertTrailingCommas: None
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
@@ -121,15 +145,19 @@ PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
+PenaltyBreakOpenParenthesis: 0
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
-PenaltyReturnTypeOnItsOwnLine: 60
+PenaltyReturnTypeOnItsOwnLine: 1000
PenaltyIndentedWhitespace: 0
PointerAlignment: Right
PPIndentWidth: -1
ReferenceAlignment: Pointer
ReflowComments: true
+RemoveBracesLLVM: false
+RequiresClausePosition: OwnLine
+SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SortIncludes: CaseSensitive
SortJavaStaticImport: Before
@@ -143,6 +171,16 @@ SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
+SpaceBeforeParensOptions:
+ AfterControlStatements: true
+ AfterForeachMacros: true
+ AfterFunctionDefinitionName: false
+ AfterFunctionDeclarationName: false
+ AfterIfMacros: true
+ AfterOverloadedOperator: false
+ AfterRequiresInClause: false
+ AfterRequiresInExpression: false
+ BeforeNonEmptyParentheses: false
SpaceAroundPointerQualifiers: Default
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
@@ -165,7 +203,7 @@ StatementAttributeLikeMacros:
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
-TabWidth: 8
+TabWidth: 4
UseCRLF: false
UseTab: Never
WhitespaceSensitiveMacros:
diff --git a/Problems/0001.cpp b/Problems/0001.cpp
@@ -1,12 +1,12 @@
class Solution {
-public:
- vector<int> twoSum(vector<int> &nums, int target) {
- unordered_map<int, int> um;
- for (int i = 0; i < nums.size(); i++)
- if (um.find(target - nums[i]) != um.end())
- return {um[target - nums[i]], i};
- else
- um.insert(make_pair(nums[i], i));
- return {};
- }
+ public:
+ vector<int> twoSum(vector<int> &nums, int target) {
+ unordered_map<int, int> um;
+ for (int i = 0; i < nums.size(); i++)
+ if (um.find(target - nums[i]) != um.end())
+ return {um[target - nums[i]], i};
+ else
+ um.insert(make_pair(nums[i], i));
+ return {};
+ }
};
diff --git a/Problems/0002.cpp b/Problems/0002.cpp
@@ -1,23 +1,23 @@
class Solution {
-public:
- ListNode *addTwoNumbers(ListNode *list1, ListNode *list2) {
- ListNode *head, *t;
- t = head = new ListNode();
+ public:
+ ListNode *addTwoNumbers(ListNode *list1, ListNode *list2) {
+ ListNode *head, *t;
+ t = head = new ListNode();
- int add = 0;
- while (list1 || list2 || add) {
- if (list1) {
- add += list1->val;
- list1 = list1->next;
- }
- if (list2) {
- add += list2->val;
- list2 = list2->next;
- }
- t = t->next = new ListNode(add % 10);
- add /= 10;
- }
+ int add = 0;
+ while (list1 || list2 || add) {
+ if (list1) {
+ add += list1->val;
+ list1 = list1->next;
+ }
+ if (list2) {
+ add += list2->val;
+ list2 = list2->next;
+ }
+ t = t->next = new ListNode(add % 10);
+ add /= 10;
+ }
- return head->next;
- }
+ return head->next;
+ }
};
diff --git a/Problems/0003.cpp b/Problems/0003.cpp
@@ -1,13 +1,14 @@
class Solution {
-public:
- int lengthOfLongestSubstring(string s) {
- int maxi = 0;
- unordered_set<char> us;
- for (int i = 0, j = 0; j < size(s); j++) {
- while (us.count(s[j])) us.erase(s[i++]);
- maxi = max(j - i + 1, maxi);
- us.insert(s[j]);
+ public:
+ int lengthOfLongestSubstring(string s) {
+ int maxi = 0;
+ unordered_set<char> us;
+ for (int i = 0, j = 0; j < size(s); j++) {
+ while (us.count(s[j]))
+ us.erase(s[i++]);
+ maxi = max(j - i + 1, maxi);
+ us.insert(s[j]);
+ }
+ return maxi;
}
- return maxi;
- }
};
diff --git a/Problems/0005.cpp b/Problems/0005.cpp
@@ -1,20 +1,21 @@
class Solution {
- const string len(const string &s, int a, int b) {
- while (a >= 0 && b < s.size() && s[a] == s[b]) a--, b++;
- return s.substr(a + 1, b - a - 1);
- }
+ const string len(const string &s, int a, int b) {
+ while (a >= 0 && b < s.size() && s[a] == s[b])
+ a--, b++;
+ return s.substr(a + 1, b - a - 1);
+ }
-public:
- string longestPalindrome(string s) {
- string res = "", t;
- s.push_back(' ');
- for (int i = 0; i < s.size(); i++) {
- t = len(s, i, i);
- if (t.size() > res.size()) res = t;
- if (s[i] != s[i + 1]) continue;
- t = len(s, i, i + 1);
- if (t.size() > res.size()) res = t;
+ public:
+ string longestPalindrome(string s) {
+ string res = "", t;
+ s.push_back(' ');
+ for (int i = 0; i < s.size(); i++) {
+ t = len(s, i, i);
+ if (t.size() > res.size()) res = t;
+ if (s[i] != s[i + 1]) continue;
+ t = len(s, i, i + 1);
+ if (t.size() > res.size()) res = t;
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0006.cpp b/Problems/0006.cpp
@@ -1,18 +1,19 @@
class Solution {
-public:
- string convert(string s, int numRows) {
- if (numRows == 1) return s;
- vector<string> mat(numRows);
+ public:
+ string convert(string s, int numRows) {
+ if (numRows == 1) return s;
+ vector<string> mat(numRows);
- int mode = 1, x = 0;
- for (char c : s) {
- mat[x].push_back(c);
- x += mode;
- if (x == numRows - 1 || x == 0) mode *= -1;
- }
+ int mode = 1, x = 0;
+ for (char c : s) {
+ mat[x].push_back(c);
+ x += mode;
+ if (x == numRows - 1 || x == 0) mode *= -1;
+ }
- string res = "";
- for (const auto &r : mat) res += r;
- return res;
- }
+ string res = "";
+ for (const auto &r : mat)
+ res += r;
+ return res;
+ }
};
diff --git a/Problems/0007.cpp b/Problems/0007.cpp
@@ -1,19 +1,21 @@
class Solution {
-public:
- int reverse(int x) {
- if (x == INT_MIN || x == INT_MAX) return 0;
+ public:
+ int reverse(int x) {
+ if (x == INT_MIN || x == INT_MAX) return 0;
- bool neg = false;
- unsigned long res = 0;
+ bool neg = false;
+ unsigned long res = 0;
- if (x < 0) {
- neg = true;
- x = -x;
- }
+ if (x < 0) {
+ neg = true;
+ x = -x;
+ }
- do { res = res * 10 + x % 10; } while ((x /= 10) > 0);
+ do {
+ res = res * 10 + x % 10;
+ } while ((x /= 10) > 0);
- if (res > INT_MAX) return 0;
- return !neg ? res : -res;
- }
+ if (res > INT_MAX) return 0;
+ return !neg ? res : -res;
+ }
};
diff --git a/Problems/0008.cpp b/Problems/0008.cpp
@@ -1,23 +1,24 @@
class Solution {
-public:
- int myAtoi(string s) {
- if (s == "-91283472332") return INT_MIN;
- cout << INT_MAX << endl;
- int i = 0, neg = 0, res = 0;
- while (isspace(s[i])) i++;
- if (s[i] == '-')
- neg = 1, i++;
- else if (s[i] == '+')
- i++;
+ public:
+ int myAtoi(string s) {
+ if (s == "-91283472332") return INT_MIN;
+ cout << INT_MAX << endl;
+ int i = 0, neg = 0, res = 0;
+ while (isspace(s[i]))
+ i++;
+ if (s[i] == '-')
+ neg = 1, i++;
+ else if (s[i] == '+')
+ i++;
- while (isdigit(s[i])) {
- int digit = s[i++] - '0';
- if (res > (INT_MAX / 10) || (res == (INT_MAX / 10) && digit > 7)) {
- return neg ? INT_MIN : INT_MAX;
- }
- res *= 10, res += digit;
- }
+ while (isdigit(s[i])) {
+ int digit = s[i++] - '0';
+ if (res > (INT_MAX / 10) || (res == (INT_MAX / 10) && digit > 7)) {
+ return neg ? INT_MIN : INT_MAX;
+ }
+ res *= 10, res += digit;
+ }
- return neg ? -res : res;
- }
+ return neg ? -res : res;
+ }
};
diff --git a/Problems/0009.cpp b/Problems/0009.cpp
@@ -1,9 +1,11 @@
class Solution {
-public:
- bool isPalindrome(int x) {
- if (x < 0 || (x != 0 && x % 10 == 0)) return false;
- int sum = 0;
- do { sum = sum * 10 + x % 10; } while ((x /= 10) > sum);
- return (x == sum) || (x == sum / 10);
- }
+ public:
+ bool isPalindrome(int x) {
+ if (x < 0 || (x != 0 && x % 10 == 0)) return false;
+ int sum = 0;
+ do {
+ sum = sum * 10 + x % 10;
+ } while ((x /= 10) > sum);
+ return (x == sum) || (x == sum / 10);
+ }
};
diff --git a/Problems/0011.cpp b/Problems/0011.cpp
@@ -1,16 +1,17 @@
class Solution {
-public:
- int trap(vector<int> &height) {
- int ans = 0, n = height.size(), maxi, m1, m2;
- vector<int> mleft(n), mright(n);
+ public:
+ int trap(vector<int> &height) {
+ int ans = 0, n = height.size(), maxi, m1, m2;
+ vector<int> mleft(n), mright(n);
- m1 = m2 = INT_MIN;
- for (int i = 0; i < n; i++) {
- mleft[i] = m1 = max(m1, height[i]);
- mright[n - i - 1] = m2 = max(m2, height[n - i - 1]);
- }
+ m1 = m2 = INT_MIN;
+ for (int i = 0; i < n; i++) {
+ mleft[i] = m1 = max(m1, height[i]);
+ mright[n - i - 1] = m2 = max(m2, height[n - i - 1]);
+ }
- for (int i = 1; i < n - 1; i++) ans += min(mleft[i], mright[i]) - height[i];
- return ans;
- }
+ for (int i = 1; i < n - 1; i++)
+ ans += min(mleft[i], mright[i]) - height[i];
+ return ans;
+ }
};
diff --git a/Problems/0012.cpp b/Problems/0012.cpp
@@ -1,17 +1,19 @@
class Solution {
-public:
- vector<vector<string>> vvs = {
- {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
- {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
- {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
- {"", "M", "MM", "MMM", "*", "*", "*", "*", "*", "*"},
- };
+ public:
+ vector<vector<string>> vvs = {
+ {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
+ {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
+ {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
+ {"", "M", "MM", "MMM", "*", "*", "*", "*", "*", "*"},
+ };
- string intToRoman(int num) {
- int exp = 0;
- string res = "";
- do { res = vvs[exp++][num % 10] + res; } while ((num /= 10) > 0);
+ string intToRoman(int num) {
+ int exp = 0;
+ string res = "";
+ do {
+ res = vvs[exp++][num % 10] + res;
+ } while ((num /= 10) > 0);
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0013.cpp b/Problems/0013.cpp
@@ -1,31 +1,31 @@
class Solution {
-public:
- int value(char c) {
- switch (c) {
- case 'I': return 1;
- case 'V': return 5;
- case 'X': return 10;
- case 'L': return 50;
- case 'C': return 100;
- case 'D': return 500;
- case 'M': return 1000;
- default: return -10000;
+ public:
+ int value(char c) {
+ switch (c) {
+ case 'I': return 1;
+ case 'V': return 5;
+ case 'X': return 10;
+ case 'L': return 50;
+ case 'C': return 100;
+ case 'D': return 500;
+ case 'M': return 1000;
+ default: return -10000;
+ }
}
- }
- int romanToInt(string s) {
- int size = s.size();
- int res = 0;
- for (int i = 0; i < size - 1; i++) {
- int a = value(s[i]);
- int b = value(s[i + 1]);
- if (a >= b)
- res += a;
- else
- res -= a;
- }
- res += value(s[size - 1]);
+ int romanToInt(string s) {
+ int size = s.size();
+ int res = 0;
+ for (int i = 0; i < size - 1; i++) {
+ int a = value(s[i]);
+ int b = value(s[i + 1]);
+ if (a >= b)
+ res += a;
+ else
+ res -= a;
+ }
+ res += value(s[size - 1]);
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0014.cpp b/Problems/0014.cpp
@@ -1,15 +1,16 @@
class Solution {
-public:
- string longestCommonPrefix(vector<string> &strs) {
- int mlen = 200;
- for (string &s : strs) mlen = min(mlen, (int)s.size());
+ public:
+ string longestCommonPrefix(vector<string> &strs) {
+ int mlen = 200;
+ for (string &s : strs)
+ mlen = min(mlen, (int)s.size());
- string res = "";
- for (int i = 0; i < mlen; i++) {
- for (int j = 1; j < strs.size(); j++)
- if (strs[j][i] != strs[0][i]) return res;
- res += strs[0][i];
+ string res = "";
+ for (int i = 0; i < mlen; i++) {
+ for (int j = 1; j < strs.size(); j++)
+ if (strs[j][i] != strs[0][i]) return res;
+ res += strs[0][i];
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0015.cpp b/Problems/0015.cpp
@@ -1,28 +1,30 @@
class Solution {
-public:
- vector<vector<int>> threeSum(vector<int> &num) {
- sort(num.begin(), num.end());
+ public:
+ vector<vector<int>> threeSum(vector<int> &num) {
+ sort(num.begin(), num.end());
- vector<vector<int>> res;
- for (int i = 0; i < num.size();) {
- int target = -num[i], start = i + 1, end = num.size() - 1;
+ vector<vector<int>> res;
+ for (int i = 0; i < num.size();) {
+ int target = -num[i], start = i + 1, end = num.size() - 1;
- while (start < end) {
- int sum = num[start] + num[end];
- if (sum < target)
- start++;
- else if (sum > target)
- end--;
- else {
- res.push_back({num[i], num[start], num[end]});
- while (start < end && num[start] == res.back()[1]) start++;
- while (start < end && num[end] == res.back()[2]) end--;
+ while (start < end) {
+ int sum = num[start] + num[end];
+ if (sum < target)
+ start++;
+ else if (sum > target)
+ end--;
+ else {
+ res.push_back({num[i], num[start], num[end]});
+ while (start < end && num[start] == res.back()[1])
+ start++;
+ while (start < end && num[end] == res.back()[2])
+ end--;
+ }
+ }
+ for (i++; i < num.size() && num[i] == num[i - 1]; i++)
+ ;
}
- }
- for (i++; i < num.size() && num[i] == num[i - 1]; i++)
- ;
- }
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0016.cpp b/Problems/0016.cpp
@@ -1,20 +1,20 @@
class Solution {
-public:
- int threeSumClosest(vector<int> &nums, int target) {
- int n = nums.size(), delta = INT_MAX / 2, res = 0;
- sort(nums.begin(), nums.end());
- for (int i = 0; i < n; i++) {
- int j = i + 1;
- int k = n - 1;
- while (j < k) {
- int sum = nums[i] + nums[j] + nums[k];
- if (abs(target - sum) < delta) {
- delta = abs(target - sum);
- res = sum;
+ public:
+ int threeSumClosest(vector<int> &nums, int target) {
+ int n = nums.size(), delta = INT_MAX / 2, res = 0;
+ sort(nums.begin(), nums.end());
+ for (int i = 0; i < n; i++) {
+ int j = i + 1;
+ int k = n - 1;
+ while (j < k) {
+ int sum = nums[i] + nums[j] + nums[k];
+ if (abs(target - sum) < delta) {
+ delta = abs(target - sum);
+ res = sum;
+ }
+ (sum > target) ? k-- : j++;
+ }
}
- (sum > target) ? k-- : j++;
- }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0017.cpp b/Problems/0017.cpp
@@ -1,17 +1,16 @@
class Solution {
-public:
- vector<string> letterCombinations(string digits) {
- vector<string> um = {"abc", "def", "ghi", "jkl",
- "mno", "pqrs", "tuv", "wxyz"},
- res = {""};
+ public:
+ vector<string> letterCombinations(string digits) {
+ vector<string> um = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}, res = {""};
- for (char d : digits) {
- vector<string> tmp;
- for (char l : um[d - '2'])
- for (const string &s : res) tmp.push_back(s + l);
- res = tmp;
- }
+ for (char d : digits) {
+ vector<string> tmp;
+ for (char l : um[d - '2'])
+ for (const string &s : res)
+ tmp.push_back(s + l);
+ res = tmp;
+ }
- return res.size() > 1 ? res : vector<string>();
- }
+ return res.size() > 1 ? res : vector<string>();
+ }
};
diff --git a/Problems/0018.cpp b/Problems/0018.cpp
@@ -1,30 +1,33 @@
class Solution {
-public:
- vector<vector<int>> fourSum(vector<int> &nums, int target) {
- vector<vector<int>> res;
- int n = nums.size();
+ public:
+ vector<vector<int>> fourSum(vector<int> &nums, int target) {
+ vector<vector<int>> res;
+ int n = nums.size();
- sort(nums.begin(), nums.end());
- for (int i = 0; i < n; i++) {
- for (int j = i + 1; j < n; j++) {
- long long goal = (long long)target - nums[i] - nums[j];
- int k = j + 1, l = n - 1;
- while (k < l) {
- long long crnt = nums[k] + nums[l];
- if (crnt > goal)
- l--;
- else if (crnt < goal)
- k++;
- else {
- res.push_back({nums[i], nums[j], nums[k], nums[l]});
- k++, l--;
- while (k < l && nums[l] == nums[l + 1]) l--;
- }
+ sort(nums.begin(), nums.end());
+ for (int i = 0; i < n; i++) {
+ for (int j = i + 1; j < n; j++) {
+ long long goal = (long long)target - nums[i] - nums[j];
+ int k = j + 1, l = n - 1;
+ while (k < l) {
+ long long crnt = nums[k] + nums[l];
+ if (crnt > goal)
+ l--;
+ else if (crnt < goal)
+ k++;
+ else {
+ res.push_back({nums[i], nums[j], nums[k], nums[l]});
+ k++, l--;
+ while (k < l && nums[l] == nums[l + 1])
+ l--;
+ }
+ }
+ while (j + 1 < n && nums[j] == nums[j + 1])
+ ++j;
+ }
+ while (i + 1 < n && nums[i] == nums[i + 1])
+ ++i;
}
- while (j + 1 < n && nums[j] == nums[j + 1]) ++j;
- }
- while (i + 1 < n && nums[i] == nums[i + 1]) ++i;
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0019.cpp b/Problems/0019.cpp
@@ -1,19 +1,19 @@
class Solution {
-public:
- ListNode *removeNthFromEnd(ListNode *head, int n) {
- ListNode *b = head;
+ public:
+ ListNode *removeNthFromEnd(ListNode *head, int n) {
+ ListNode *b = head;
- n++;
- for (ListNode *a = head; a; a = a->next) {
- if (!n)
- b = b->next;
- else
- n--;
+ n++;
+ for (ListNode *a = head; a; a = a->next) {
+ if (!n)
+ b = b->next;
+ else
+ n--;
+ }
+ if (n)
+ head = head->next;
+ else
+ b->next = b->next->next;
+ return head;
}
- if (n)
- head = head->next;
- else
- b->next = b->next->next;
- return head;
- }
};
diff --git a/Problems/0020.cpp b/Problems/0020.cpp
@@ -1,30 +1,30 @@
class Solution {
- char is_open(char c) { return c == '(' || c == '[' || c == '{'; }
- char get_open_pair(char c) {
- switch (c) {
- case ')': return '(';
- case ']': return '[';
- case '}': return '{';
- default: return 0;
+ char is_open(char c) { return c == '(' || c == '[' || c == '{'; }
+ char get_open_pair(char c) {
+ switch (c) {
+ case ')': return '(';
+ case ']': return '[';
+ case '}': return '{';
+ default: return 0;
+ }
}
- }
-public:
- bool isValid(string s) {
- stack<char> st;
+ public:
+ bool isValid(string s) {
+ stack<char> st;
- char t;
- for (auto c : s)
- if (is_open(c))
- st.push(c);
- else if ((t = get_open_pair(c)))
- if (!st.empty() && st.top() == t)
- st.pop();
- else
- return false;
- else
- return false;
+ char t;
+ for (auto c : s)
+ if (is_open(c))
+ st.push(c);
+ else if ((t = get_open_pair(c)))
+ if (!st.empty() && st.top() == t)
+ st.pop();
+ else
+ return false;
+ else
+ return false;
- return st.empty();
- }
+ return st.empty();
+ }
};
diff --git a/Problems/0021.cpp b/Problems/0021.cpp
@@ -1,19 +1,19 @@
class Solution {
-public:
- ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) {
- ListNode head, *t = &head;
+ public:
+ ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) {
+ ListNode head, *t = &head;
- while (list1 && list2) {
- if (list1->val < list2->val) {
- t = t->next = list1;
- list1 = list1->next;
- } else {
- t = t->next = list2;
- list2 = list2->next;
- }
- }
+ while (list1 && list2) {
+ if (list1->val < list2->val) {
+ t = t->next = list1;
+ list1 = list1->next;
+ } else {
+ t = t->next = list2;
+ list2 = list2->next;
+ }
+ }
- t->next = list1 ? list1 : list2;
- return head.next;
- }
+ t->next = list1 ? list1 : list2;
+ return head.next;
+ }
};
diff --git a/Problems/0022.cpp b/Problems/0022.cpp
@@ -1,31 +1,31 @@
class Solution {
- vector<string> res;
- stack<char> st;
- string crnt = "";
+ vector<string> res;
+ stack<char> st;
+ string crnt = "";
- void dfs(int n) {
- static const char o = '(', c = ')';
+ void dfs(int n) {
+ static const char o = '(', c = ')';
- if (!n) {
- if (st.empty()) res.push_back(crnt);
- return;
- }
+ if (!n) {
+ if (st.empty()) res.push_back(crnt);
+ return;
+ }
- st.push(o), crnt += o;
- dfs(n - 1);
- st.pop(), crnt.pop_back();
+ st.push(o), crnt += o;
+ dfs(n - 1);
+ st.pop(), crnt.pop_back();
- if (st.empty()) return;
+ if (st.empty()) return;
- crnt += c, st.pop();
- dfs(n - 1);
- crnt.pop_back();
- st.push(c);
- }
+ crnt += c, st.pop();
+ dfs(n - 1);
+ crnt.pop_back();
+ st.push(c);
+ }
-public:
- vector<string> generateParenthesis(int n) {
- dfs(n * 2);
- return res;
- }
+ public:
+ vector<string> generateParenthesis(int n) {
+ dfs(n * 2);
+ return res;
+ }
};
diff --git a/Problems/0023.cpp b/Problems/0023.cpp
@@ -1,48 +1,48 @@
// Naive solution, barely passed
class Solution {
-public:
- ListNode *mergeKLists(vector<ListNode *> &lists) {
- ListNode *dummy, *tmp;
- tmp = dummy = new ListNode;
+ public:
+ ListNode *mergeKLists(vector<ListNode *> &lists) {
+ ListNode *dummy, *tmp;
+ tmp = dummy = new ListNode;
- while (true) {
- int mini = INT_MAX, index = -1;
- for (int i = 0; i < lists.size(); i++) {
- if (lists[i] && lists[i]->val < mini) {
- index = i;
- mini = lists[i]->val;
+ while (true) {
+ int mini = INT_MAX, index = -1;
+ for (int i = 0; i < lists.size(); i++) {
+ if (lists[i] && lists[i]->val < mini) {
+ index = i;
+ mini = lists[i]->val;
+ }
+ }
+ if (index == -1) break;
+ ListNode *t = lists[index];
+ lists[index] = lists[index]->next;
+ tmp = tmp->next = t;
}
- }
- if (index == -1) break;
- ListNode *t = lists[index];
- lists[index] = lists[index]->next;
- tmp = tmp->next = t;
+ return dummy->next;
}
- return dummy->next;
- }
};
// Proper solution
class Solution {
- typedef pair<int, int> pii;
+ typedef pair<int, int> pii;
-public:
- ListNode *mergeKLists(vector<ListNode *> &lists) {
- ListNode *dummy, *tmp;
- tmp = dummy = new ListNode;
+ public:
+ ListNode *mergeKLists(vector<ListNode *> &lists) {
+ ListNode *dummy, *tmp;
+ tmp = dummy = new ListNode;
- auto cmp = [](const pii &a, const pii &b) { return a.first > b.first; };
- priority_queue<pii, vector<pii>, decltype(cmp)> pq(cmp);
- for (int i = 0; i < lists.size(); i++)
- if (lists[i]) pq.push({lists[i]->val, i});
- while (!pq.empty()) {
- int index = pq.top().second;
- pq.pop();
- ListNode *t = lists[index];
- lists[index] = lists[index]->next;
- if (lists[index]) pq.push({lists[index]->val, index});
- tmp = tmp->next = t;
+ auto cmp = [](const pii &a, const pii &b) { return a.first > b.first; };
+ priority_queue<pii, vector<pii>, decltype(cmp)> pq(cmp);
+ for (int i = 0; i < lists.size(); i++)
+ if (lists[i]) pq.push({lists[i]->val, i});
+ while (!pq.empty()) {
+ int index = pq.top().second;
+ pq.pop();
+ ListNode *t = lists[index];
+ lists[index] = lists[index]->next;
+ if (lists[index]) pq.push({lists[index]->val, index});
+ tmp = tmp->next = t;
+ }
+ return dummy->next;
}
- return dummy->next;
- }
};
diff --git a/Problems/0024.cpp b/Problems/0024.cpp
@@ -1,14 +1,14 @@
class Solution {
-public:
- ListNode *swapPairs(ListNode *head) {
- ListNode *d = new ListNode(-1, head);
- for (ListNode *p = d; p->next && p->next->next;) {
- ListNode *t = p->next;
- p->next = p->next->next;
- t->next = p->next->next;
- p->next->next = t;
- p = t;
+ public:
+ ListNode *swapPairs(ListNode *head) {
+ ListNode *d = new ListNode(-1, head);
+ for (ListNode *p = d; p->next && p->next->next;) {
+ ListNode *t = p->next;
+ p->next = p->next->next;
+ t->next = p->next->next;
+ p->next->next = t;
+ p = t;
+ }
+ return d->next;
}
- return d->next;
- }
};
diff --git a/Problems/0025.cpp b/Problems/0025.cpp
@@ -1,21 +1,21 @@
class Solution {
-public:
- ListNode *reverseKGroup(ListNode *head, int k) {
- stack<ListNode *> st;
- ListNode *tmp, *dummy, *next;
+ public:
+ ListNode *reverseKGroup(ListNode *head, int k) {
+ stack<ListNode *> st;
+ ListNode *tmp, *dummy, *next;
- tmp = dummy = new ListNode(-1, nullptr);
- for (ListNode *p = head; p; p = next) {
- next = p->next;
- st.push(p);
- if (st.size() == k) {
- while (!st.empty()) {
- tmp = tmp->next = st.top();
- st.pop();
+ tmp = dummy = new ListNode(-1, nullptr);
+ for (ListNode *p = head; p; p = next) {
+ next = p->next;
+ st.push(p);
+ if (st.size() == k) {
+ while (!st.empty()) {
+ tmp = tmp->next = st.top();
+ st.pop();
+ }
+ tmp->next = next;
+ }
}
- tmp->next = next;
- }
+ return dummy->next;
}
- return dummy->next;
- }
};
diff --git a/Problems/0026.cpp b/Problems/0026.cpp
@@ -1,10 +1,10 @@
class Solution {
-public:
- int removeDuplicates(vector<int> &nums) {
- int j = 1;
- for (int i = 1; i < nums.size(); i++) {
- if (nums[i - 1] != nums[i]) nums[j++] = nums[i];
+ public:
+ int removeDuplicates(vector<int> &nums) {
+ int j = 1;
+ for (int i = 1; i < nums.size(); i++) {
+ if (nums[i - 1] != nums[i]) nums[j++] = nums[i];
+ }
+ return j;
}
- return j;
- }
};
diff --git a/Problems/0027.cpp b/Problems/0027.cpp
@@ -1,10 +1,10 @@
class Solution {
-public:
- int removeElement(vector<int> &nums, int val) {
- int j = 0;
- for (int i = 0; i < nums.size(); i++)
- if (nums[i] != val) nums[j++] = nums[i];
+ public:
+ int removeElement(vector<int> &nums, int val) {
+ int j = 0;
+ for (int i = 0; i < nums.size(); i++)
+ if (nums[i] != val) nums[j++] = nums[i];
- return j;
- }
+ return j;
+ }
};
diff --git a/Problems/0028.cpp b/Problems/0028.cpp
@@ -1,24 +1,24 @@
class Solution {
-public:
- int strStr(string haystack, string needle) {
- vector<int> table(needle.size(), 0);
+ public:
+ int strStr(string haystack, string needle) {
+ vector<int> table(needle.size(), 0);
- int m = haystack.size(), n = needle.size();
- for (int len = 0, j = 1; j < n;) {
- if (needle[j] == needle[len])
- table[j++] = ++len;
- else if (len)
- len = table[len - 1];
- else
- table[j++] = 0;
- }
+ int m = haystack.size(), n = needle.size();
+ for (int len = 0, j = 1; j < n;) {
+ if (needle[j] == needle[len])
+ table[j++] = ++len;
+ else if (len)
+ len = table[len - 1];
+ else
+ table[j++] = 0;
+ }
- for (int i = 0, j = 0; i < m;) {
- if (haystack[i] == needle[j]) i++, j++;
- if (j == n) return i - j;
- if (i < m && haystack[i] != needle[j]) j ? j = table[j - 1] : i++;
- }
+ for (int i = 0, j = 0; i < m;) {
+ if (haystack[i] == needle[j]) i++, j++;
+ if (j == n) return i - j;
+ if (i < m && haystack[i] != needle[j]) j ? j = table[j - 1] : i++;
+ }
- return -1;
- }
+ return -1;
+ }
};
diff --git a/Problems/0029.cpp b/Problems/0029.cpp
@@ -1,35 +1,35 @@
class Solution {
-public:
- int divide(int dividend, int divisor) {
- if (divisor == INT_MIN) return dividend == INT_MIN;
- if (divisor == INT_MAX) {
- if (dividend == INT_MIN) return -1;
- if (dividend == INT_MAX) return 1;
- return 0;
- }
+ public:
+ int divide(int dividend, int divisor) {
+ if (divisor == INT_MIN) return dividend == INT_MIN;
+ if (divisor == INT_MAX) {
+ if (dividend == INT_MIN) return -1;
+ if (dividend == INT_MAX) return 1;
+ return 0;
+ }
- if (divisor == 1) return dividend;
- if (divisor == -1) {
- if (dividend == INT_MIN) return INT_MAX;
- return -dividend;
- }
+ if (divisor == 1) return dividend;
+ if (divisor == -1) {
+ if (dividend == INT_MIN) return INT_MAX;
+ return -dividend;
+ }
- int res = 0, sign = 1;
- if (divisor < 0) divisor = -divisor, sign = -sign;
- if (dividend < 0) {
- if (dividend == INT_MIN) dividend += divisor, res++;
- dividend = -dividend, sign = -sign;
- }
+ int res = 0, sign = 1;
+ if (divisor < 0) divisor = -divisor, sign = -sign;
+ if (dividend < 0) {
+ if (dividend == INT_MIN) dividend += divisor, res++;
+ dividend = -dividend, sign = -sign;
+ }
- while (dividend >= divisor) {
- long temp = divisor, count = 1;
- while (temp << 1 <= dividend) {
- temp <<= 1;
- count <<= 1;
- }
- dividend -= temp;
- res += count;
+ while (dividend >= divisor) {
+ long temp = divisor, count = 1;
+ while (temp << 1 <= dividend) {
+ temp <<= 1;
+ count <<= 1;
+ }
+ dividend -= temp;
+ res += count;
+ }
+ return sign * res;
}
- return sign * res;
- }
};
diff --git a/Problems/0031.cpp b/Problems/0031.cpp
@@ -1,17 +1,17 @@
class Solution {
-public:
- void nextPermutation(vector<int> &nums) {
- int n = nums.size(), k, l;
- for (k = n - 2; k >= 0 && nums[k] >= nums[k + 1]; k--)
- ;
+ public:
+ void nextPermutation(vector<int> &nums) {
+ int n = nums.size(), k, l;
+ for (k = n - 2; k >= 0 && nums[k] >= nums[k + 1]; k--)
+ ;
- if (k >= 0) {
- for (l = n - 1; l > k && nums[l] <= nums[k]; l--)
- ;
- swap(nums[k], nums[l]);
- reverse(nums.begin() + k + 1, nums.end());
- } else {
- reverse(nums.begin(), nums.end());
+ if (k >= 0) {
+ for (l = n - 1; l > k && nums[l] <= nums[k]; l--)
+ ;
+ swap(nums[k], nums[l]);
+ reverse(nums.begin() + k + 1, nums.end());
+ } else {
+ reverse(nums.begin(), nums.end());
+ }
}
- }
};
diff --git a/Problems/0033.cpp b/Problems/0033.cpp
@@ -1,24 +1,30 @@
class Solution {
- int binary_search(const vector<int>& nums, int target, int low, int high) {
- while(low<=high){
- int mid = low + (high-low)/2;
- if(nums[mid]==target) return mid;
- else if(nums[mid]>target) high = mid-1;
- else low = mid + 1;
+ int binary_search(const vector<int> &nums, int target, int low, int high) {
+ while (low <= high) {
+ int mid = low + (high - low) / 2;
+ if (nums[mid] == target)
+ return mid;
+ else if (nums[mid] > target)
+ high = mid - 1;
+ else
+ low = mid + 1;
+ }
+ return -1;
}
- return -1;
- }
-public:
- int search(vector<int>& nums, int target) {
- int pivot = -1;
- for(int i=0; i<nums.size()-1; i++) {
- if(nums[i] > nums[i+1]) {
- pivot = i;
- break;
+
+ public:
+ int search(vector<int> &nums, int target) {
+ int pivot = -1;
+ for (int i = 0; i < nums.size() - 1; i++) {
+ if (nums[i] > nums[i + 1]) {
+ pivot = i;
+ break;
+ }
}
- }
- if(pivot==-1) return binary_search(nums, target, 0, nums.size()-1);
- if(nums[0]<=target) return binary_search(nums, target, 0, pivot);
- else return binary_search(nums, target, pivot+1, nums.size()-1);
+ if (pivot == -1) return binary_search(nums, target, 0, nums.size() - 1);
+ if (nums[0] <= target)
+ return binary_search(nums, target, 0, pivot);
+ else
+ return binary_search(nums, target, pivot + 1, nums.size() - 1);
}
};
diff --git a/Problems/0034.cpp b/Problems/0034.cpp
@@ -1,20 +1,26 @@
class Solution {
- int binary_search(const vector<int>& nums, int target) {
- int low = 0, high = nums.size()-1;
- while(low<=high){
- int mid = low + (high-low)/2;
- if(nums[mid]==target) return mid;
- else if(nums[mid]>target) high = mid-1;
- else low = mid + 1;
+ int binary_search(const vector<int> &nums, int target) {
+ int low = 0, high = nums.size() - 1;
+ while (low <= high) {
+ int mid = low + (high - low) / 2;
+ if (nums[mid] == target)
+ return mid;
+ else if (nums[mid] > target)
+ high = mid - 1;
+ else
+ low = mid + 1;
+ }
+ return -1;
}
- return -1;
- }
-public:
- vector<int> searchRange(vector<int>& nums, int target) {
+
+ public:
+ vector<int> searchRange(vector<int> &nums, int target) {
int low, high;
low = high = binary_search(nums, target);
- while(low-1>=0 && nums[low-1] == target) low--;
- while(high+1<nums.size() && nums[high+1] == target) high++;
+ while (low - 1 >= 0 && nums[low - 1] == target)
+ low--;
+ while (high + 1 < nums.size() && nums[high + 1] == target)
+ high++;
return {low, high};
}
};
diff --git a/Problems/0035.cpp b/Problems/0035.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- int searchInsert(vector<int> &nums, int target) {
- int low = 0, high = nums.size() - 1;
- while (low <= high) {
- int mid = low + (high - low) / 2;
- if (nums[mid] == target) return mid;
- if (nums[mid] < target)
- low = mid + 1;
- else
- high = mid - 1;
+ public:
+ int searchInsert(vector<int> &nums, int target) {
+ int low = 0, high = nums.size() - 1;
+ while (low <= high) {
+ int mid = low + (high - low) / 2;
+ if (nums[mid] == target) return mid;
+ if (nums[mid] < target)
+ low = mid + 1;
+ else
+ high = mid - 1;
+ }
+ return high + 1;
}
- return high + 1;
- }
};
diff --git a/Problems/0036.cpp b/Problems/0036.cpp
@@ -1,2 +1 @@
-Formating: Problems/0036.cpp
-Formating: Problems/0074.cpp
+Formating : Problems / 0036.cpp Formating : Problems / 0074.cpp
diff --git a/Problems/0037.cpp b/Problems/0037.cpp
@@ -1,31 +1,31 @@
class Solution {
- bool check(vector<vector<char>> &board, int i, int j, char val) {
- for (int x = 0; x < 9; x++)
- if (board[x][j] == val) return false;
- for (int y = 0; y < 9; y++)
- if (board[i][y] == val) return false;
+ bool check(vector<vector<char>> &board, int i, int j, char val) {
+ for (int x = 0; x < 9; x++)
+ if (board[x][j] == val) return false;
+ for (int y = 0; y < 9; y++)
+ if (board[i][y] == val) return false;
- i = (i / 3) * 3, j = (j / 3) * 3;
- for (int x = i; x < i + 3; x++)
- for (int y = j; y < j + 3; y++)
- if (board[x][y] == val) return false;
- return true;
- }
- bool solveSudoku(vector<vector<char>> &board, int i, int j) {
- if (i == 9) return true;
- if (j == 9) return solveSudoku(board, i + 1, 0);
- if (board[i][j] != '.') return solveSudoku(board, i, j + 1);
-
- for (char c = '1'; c <= '9'; c++) {
- if (!check(board, i, j, c)) continue;
- board[i][j] = c;
- if (solveSudoku(board, i, j + 1)) return true;
- board[i][j] = '.';
+ i = (i / 3) * 3, j = (j / 3) * 3;
+ for (int x = i; x < i + 3; x++)
+ for (int y = j; y < j + 3; y++)
+ if (board[x][y] == val) return false;
+ return true;
}
+ bool solveSudoku(vector<vector<char>> &board, int i, int j) {
+ if (i == 9) return true;
+ if (j == 9) return solveSudoku(board, i + 1, 0);
+ if (board[i][j] != '.') return solveSudoku(board, i, j + 1);
+
+ for (char c = '1'; c <= '9'; c++) {
+ if (!check(board, i, j, c)) continue;
+ board[i][j] = c;
+ if (solveSudoku(board, i, j + 1)) return true;
+ board[i][j] = '.';
+ }
- return false;
- }
+ return false;
+ }
-public:
- void solveSudoku(vector<vector<char>> &board) { solveSudoku(board, 0, 0); }
+ public:
+ void solveSudoku(vector<vector<char>> &board) { solveSudoku(board, 0, 0); }
};
diff --git a/Problems/0038.cpp b/Problems/0038.cpp
@@ -1,21 +1,21 @@
class Solution {
-public:
- string countAndSay(int n) {
- string crnt = "1";
- for (int i = 1; i < n; i++) {
- string res = "";
- int c = crnt.front(), count = 1;
- for (int i = 1; i < crnt.size(); i++) {
- if (crnt[i] == c)
- count++;
- else {
- res += to_string(count) + (char)c;
- count = 1;
- c = crnt[i];
+ public:
+ string countAndSay(int n) {
+ string crnt = "1";
+ for (int i = 1; i < n; i++) {
+ string res = "";
+ int c = crnt.front(), count = 1;
+ for (int i = 1; i < crnt.size(); i++) {
+ if (crnt[i] == c)
+ count++;
+ else {
+ res += to_string(count) + (char)c;
+ count = 1;
+ c = crnt[i];
+ }
+ }
+ crnt = res + to_string(count) + (char)c;
}
- }
- crnt = res + to_string(count) + (char)c;
+ return crnt;
}
- return crnt;
- }
};
diff --git a/Problems/0039.cpp b/Problems/0039.cpp
@@ -1,23 +1,23 @@
class Solution {
- vector<vector<int>> res;
- vector<int> crnt;
+ vector<vector<int>> res;
+ vector<int> crnt;
- void rec(vector<int> &candidates, int target, int sum, int start = 0) {
- if (sum == target)
- res.push_back(crnt);
- else if (sum < target) {
- for (int i = start; i < candidates.size(); i++) {
- crnt.push_back(candidates[i]);
- rec(candidates, target, sum + candidates[i], i);
- crnt.pop_back();
- }
+ void rec(vector<int> &candidates, int target, int sum, int start = 0) {
+ if (sum == target)
+ res.push_back(crnt);
+ else if (sum < target) {
+ for (int i = start; i < candidates.size(); i++) {
+ crnt.push_back(candidates[i]);
+ rec(candidates, target, sum + candidates[i], i);
+ crnt.pop_back();
+ }
+ }
}
- }
-public:
- vector<vector<int>> combinationSum(vector<int> &candidates, int target) {
- sort(candidates.begin(), candidates.end());
- rec(candidates, target, 0);
- return res;
- }
+ public:
+ vector<vector<int>> combinationSum(vector<int> &candidates, int target) {
+ sort(candidates.begin(), candidates.end());
+ rec(candidates, target, 0);
+ return res;
+ }
};
diff --git a/Problems/0040.cpp b/Problems/0040.cpp
@@ -1,24 +1,24 @@
class Solution {
- vector<vector<int>> res;
- vector<int> crnt;
+ vector<vector<int>> res;
+ vector<int> crnt;
- void rec(vector<int> &candidates, int target, int sum, int start = 0) {
- if (sum == target)
- res.push_back(crnt);
- else if (sum < target) {
- for (int i = start; i < candidates.size(); i++) {
- if (i != start && candidates[i] == candidates[i - 1]) continue;
- crnt.push_back(candidates[i]);
- rec(candidates, target, sum + candidates[i], i + 1);
- crnt.pop_back();
- }
+ void rec(vector<int> &candidates, int target, int sum, int start = 0) {
+ if (sum == target)
+ res.push_back(crnt);
+ else if (sum < target) {
+ for (int i = start; i < candidates.size(); i++) {
+ if (i != start && candidates[i] == candidates[i - 1]) continue;
+ crnt.push_back(candidates[i]);
+ rec(candidates, target, sum + candidates[i], i + 1);
+ crnt.pop_back();
+ }
+ }
}
- }
-public:
- vector<vector<int>> combinationSum2(vector<int> &candidates, int target) {
- sort(candidates.begin(), candidates.end());
- rec(candidates, target, 0);
- return res;
- }
+ public:
+ vector<vector<int>> combinationSum2(vector<int> &candidates, int target) {
+ sort(candidates.begin(), candidates.end());
+ rec(candidates, target, 0);
+ return res;
+ }
};
diff --git a/Problems/0043.cpp b/Problems/0043.cpp
@@ -1,27 +1,27 @@
class Solution {
-public:
- string multiply(string num1, string num2) {
- if (num1 == "0" || num2 == "0") return "0";
+ public:
+ string multiply(string num1, string num2) {
+ if (num1 == "0" || num2 == "0") return "0";
- reverse(num1.begin(), num1.end());
- reverse(num2.begin(), num2.end());
- string answer(num1.size() + num2.size(), '0');
+ reverse(num1.begin(), num1.end());
+ reverse(num2.begin(), num2.end());
+ string answer(num1.size() + num2.size(), '0');
- for (int p2 = 0; p2 < num2.size(); p2++) {
- int d2 = num2[p2] - '0';
- for (int p1 = 0; p1 < num1.size(); p1++) {
- int d1 = num1[p1] - '0';
+ for (int p2 = 0; p2 < num2.size(); p2++) {
+ int d2 = num2[p2] - '0';
+ for (int p1 = 0; p1 < num1.size(); p1++) {
+ int d1 = num1[p1] - '0';
- int numZero = p1 + p2;
- int carry = answer[numZero] - '0';
- int mul = d1 * d2 + carry;
- answer[numZero] = mul % 10 + '0';
- answer[numZero + 1] += mul / 10;
- }
- }
- if (answer.back() == '0') answer.pop_back();
+ int numZero = p1 + p2;
+ int carry = answer[numZero] - '0';
+ int mul = d1 * d2 + carry;
+ answer[numZero] = mul % 10 + '0';
+ answer[numZero + 1] += mul / 10;
+ }
+ }
+ if (answer.back() == '0') answer.pop_back();
- reverse(answer.begin(), answer.end());
- return answer;
- }
+ reverse(answer.begin(), answer.end());
+ return answer;
+ }
};
diff --git a/Problems/0044.cpp b/Problems/0044.cpp
@@ -1,21 +1,22 @@
class Solution {
-public:
- bool isMatch(string s, string p) {
- int i = 0, j = 0, n = s.size(), m = p.size();
- int last = -1, star = -1;
- while (i < n) {
- if (j < m && (s[i] == p[j] || p[j] == '?'))
- i++, j++;
- else if (j < m && p[j] == '*') {
- star = j++;
- last = i;
- } else if (star != -1) {
- j = star + 1;
- i = ++last;
- } else
- return false;
+ public:
+ bool isMatch(string s, string p) {
+ int i = 0, j = 0, n = s.size(), m = p.size();
+ int last = -1, star = -1;
+ while (i < n) {
+ if (j < m && (s[i] == p[j] || p[j] == '?'))
+ i++, j++;
+ else if (j < m && p[j] == '*') {
+ star = j++;
+ last = i;
+ } else if (star != -1) {
+ j = star + 1;
+ i = ++last;
+ } else
+ return false;
+ }
+ while (p[j] == '*' && j < m)
+ j++;
+ return j == m;
}
- while (p[j] == '*' && j < m) j++;
- return j == m;
- }
};
diff --git a/Problems/0045.cpp b/Problems/0045.cpp
@@ -1,14 +1,14 @@
class Solution {
-public:
- int jump(vector<int> &nums) {
- int n = nums.size(), limit = 0;
- vector<int> num(n);
- num[0] = 0;
- for (int i = 0; i <= limit && i < n; i++) {
- for (int j = limit + 1; j <= i + nums[i] && j < n; j++)
- num[j] = num[i] + 1;
- limit = max(limit, i + nums[i]);
+ public:
+ int jump(vector<int> &nums) {
+ int n = nums.size(), limit = 0;
+ vector<int> num(n);
+ num[0] = 0;
+ for (int i = 0; i <= limit && i < n; i++) {
+ for (int j = limit + 1; j <= i + nums[i] && j < n; j++)
+ num[j] = num[i] + 1;
+ limit = max(limit, i + nums[i]);
+ }
+ return num.back();
}
- return num.back();
- }
};
diff --git a/Problems/0046.cpp b/Problems/0046.cpp
@@ -1,25 +1,25 @@
class Solution {
- vector<vector<int>> res;
- vector<int> crnt;
- vector<bool> seen;
+ vector<vector<int>> res;
+ vector<int> crnt;
+ vector<bool> seen;
- void rec(vector<int> &nums, int n) {
- if (n == nums.size()) {
- res.push_back(crnt);
- return;
+ void rec(vector<int> &nums, int n) {
+ if (n == nums.size()) {
+ res.push_back(crnt);
+ return;
+ }
+ for (int i = 0; i < nums.size(); i++) {
+ if (seen[i]) continue;
+ seen[i] = true, crnt.push_back(nums[i]);
+ rec(nums, n + 1);
+ seen[i] = false, crnt.pop_back();
+ }
}
- for (int i = 0; i < nums.size(); i++) {
- if (seen[i]) continue;
- seen[i] = true, crnt.push_back(nums[i]);
- rec(nums, n + 1);
- seen[i] = false, crnt.pop_back();
- }
- }
-public:
- vector<vector<int>> permute(vector<int> &nums) {
- seen.resize(nums.size());
- rec(nums, 0);
- return res;
- }
+ public:
+ vector<vector<int>> permute(vector<int> &nums) {
+ seen.resize(nums.size());
+ rec(nums, 0);
+ return res;
+ }
};
diff --git a/Problems/0047.cpp b/Problems/0047.cpp
@@ -1,11 +1,11 @@
class Solution {
-public:
- vector<vector<int>> permuteUnique(vector<int> &nums) {
- vector<vector<int>> res;
- sort(nums.begin(), nums.end());
- do {
- res.push_back(nums);
- } while (next_permutation(nums.begin(), nums.end()));
- return res;
- }
+ public:
+ vector<vector<int>> permuteUnique(vector<int> &nums) {
+ vector<vector<int>> res;
+ sort(nums.begin(), nums.end());
+ do {
+ res.push_back(nums);
+ } while (next_permutation(nums.begin(), nums.end()));
+ return res;
+ }
};
diff --git a/Problems/0048.cpp b/Problems/0048.cpp
@@ -1,17 +1,18 @@
class Solution {
- typedef vector<vector<int>> Mat;
- int n;
+ typedef vector<vector<int>> Mat;
+ int n;
- void swap_group(Mat &matrix, int x, int y) {
- swap(matrix[x][y], matrix[y][n - x - 1]);
- swap(matrix[n - x - 1][n - y - 1], matrix[n - y - 1][x]);
- swap(matrix[x][y], matrix[n - x - 1][n - y - 1]);
- }
+ void swap_group(Mat &matrix, int x, int y) {
+ swap(matrix[x][y], matrix[y][n - x - 1]);
+ swap(matrix[n - x - 1][n - y - 1], matrix[n - y - 1][x]);
+ swap(matrix[x][y], matrix[n - x - 1][n - y - 1]);
+ }
-public:
- void rotate(Mat &matrix) {
- n = matrix.size();
- for (int i = 0; i <= n / 2; i++)
- for (int j = i; j < n - i - 1; j++) swap_group(matrix, i, j);
- }
+ public:
+ void rotate(Mat &matrix) {
+ n = matrix.size();
+ for (int i = 0; i <= n / 2; i++)
+ for (int j = i; j < n - i - 1; j++)
+ swap_group(matrix, i, j);
+ }
};
diff --git a/Problems/0049.cpp b/Problems/0049.cpp
@@ -1,20 +1,22 @@
class Solution {
-public:
- vector<vector<string>> groupAnagrams(vector<string> &strs) {
- vector<vector<string>> res;
- unordered_map<unsigned long long, int> um;
- for (int i = 0; i < strs.size(); i++) {
- unsigned long long hash = 0;
- vector<int> m(26, 0);
+ public:
+ vector<vector<string>> groupAnagrams(vector<string> &strs) {
+ vector<vector<string>> res;
+ unordered_map<unsigned long long, int> um;
+ for (int i = 0; i < strs.size(); i++) {
+ unsigned long long hash = 0;
+ vector<int> m(26, 0);
- for (char c : strs[i]) m[c - 'a']++;
- for (int i = 0; i < 26; i++) hash = hash * 100 + m[i];
- if (um.find(hash) == um.end()) {
- um[hash] = res.size();
- res.push_back({strs[i]});
- } else
- res[um[hash]].push_back(strs[i]);
+ for (char c : strs[i])
+ m[c - 'a']++;
+ for (int i = 0; i < 26; i++)
+ hash = hash * 100 + m[i];
+ if (um.find(hash) == um.end()) {
+ um[hash] = res.size();
+ res.push_back({strs[i]});
+ } else
+ res[um[hash]].push_back(strs[i]);
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0050.cpp b/Problems/0050.cpp
@@ -1,8 +1,8 @@
class Solution {
-public:
- double myPow(double x, int n) {
- if (n == 0) return 1;
- if (n < 0) return 1 / x * myPow(1 / x, -(n + 1));
- return (n % 2 == 0) ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2);
- }
+ public:
+ double myPow(double x, int n) {
+ if (n == 0) return 1;
+ if (n < 0) return 1 / x * myPow(1 / x, -(n + 1));
+ return (n % 2 == 0) ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2);
+ }
};
diff --git a/Problems/0051.cpp b/Problems/0051.cpp
@@ -1,53 +1,46 @@
class Solution {
- vector<vector<string>> res;
- vector<string> board;
- unordered_set<int> used;
- int n;
+ vector<vector<string>> res;
+ vector<string> board;
+ unordered_set<int> used;
+ int n;
- bool valid(int row, int col) {
- return row >= 0 && row < n && col >= 0 && col < n;
- }
+ bool valid(int row, int col) { return row >= 0 && row < n && col >= 0 && col < n; }
- bool safe(int row, int col) {
- static vector<pair<int, int>> ofsts = {
- { 1, 1},
- { 1, -1},
- {-1, 1},
- {-1, -1}
- };
+ bool safe(int row, int col) {
+ static vector<pair<int, int>> ofsts = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
- if (used.count(col)) return false;
- for (auto &ofst : ofsts) {
- int a = row + ofst.first, b = col + ofst.second;
- while (valid(a, b)) {
- if (board[a][b] == 'Q') return false;
- a += ofst.first, b += ofst.second;
- }
+ if (used.count(col)) return false;
+ for (auto &ofst : ofsts) {
+ int a = row + ofst.first, b = col + ofst.second;
+ while (valid(a, b)) {
+ if (board[a][b] == 'Q') return false;
+ a += ofst.first, b += ofst.second;
+ }
+ }
+ return true;
}
- return true;
- }
- void rec(int row) {
- if (row == n) {
- res.push_back(board);
- return;
- }
+ void rec(int row) {
+ if (row == n) {
+ res.push_back(board);
+ return;
+ }
- for (int i = 0; i < n; i++) {
- if (!safe(row, i)) continue;
- used.insert(i);
- board[row][i] = 'Q';
- rec(row + 1);
- used.erase(i);
- board[row][i] = '.';
+ for (int i = 0; i < n; i++) {
+ if (!safe(row, i)) continue;
+ used.insert(i);
+ board[row][i] = 'Q';
+ rec(row + 1);
+ used.erase(i);
+ board[row][i] = '.';
+ }
}
- }
-public:
- vector<vector<string>> solveNQueens(int n) {
- this->n = n;
- board = vector<string>(n, string(n, '.'));
- rec(0);
- return res;
- }
+ public:
+ vector<vector<string>> solveNQueens(int n) {
+ this->n = n;
+ board = vector<string>(n, string(n, '.'));
+ rec(0);
+ return res;
+ }
};
diff --git a/Problems/0052.cpp b/Problems/0052.cpp
@@ -1,52 +1,45 @@
class Solution {
- vector<string> board;
- unordered_set<int> used;
- int n, res;
+ vector<string> board;
+ unordered_set<int> used;
+ int n, res;
- bool valid(int row, int col) {
- return row >= 0 && row < n && col >= 0 && col < n;
- }
+ bool valid(int row, int col) { return row >= 0 && row < n && col >= 0 && col < n; }
- bool safe(int row, int col) {
- static vector<pair<int, int>> ofsts = {
- { 1, 1},
- { 1, -1},
- {-1, 1},
- {-1, -1}
- };
+ bool safe(int row, int col) {
+ static vector<pair<int, int>> ofsts = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
- if (used.count(col)) return false;
- for (auto &ofst : ofsts) {
- int a = row + ofst.first, b = col + ofst.second;
- while (valid(a, b)) {
- if (board[a][b] == 'Q') return false;
- a += ofst.first, b += ofst.second;
- }
+ if (used.count(col)) return false;
+ for (auto &ofst : ofsts) {
+ int a = row + ofst.first, b = col + ofst.second;
+ while (valid(a, b)) {
+ if (board[a][b] == 'Q') return false;
+ a += ofst.first, b += ofst.second;
+ }
+ }
+ return true;
}
- return true;
- }
- void rec(int row) {
- if (row == n) {
- res++;
- return;
- }
+ void rec(int row) {
+ if (row == n) {
+ res++;
+ return;
+ }
- for (int i = 0; i < n; i++) {
- if (!safe(row, i)) continue;
- used.insert(i);
- board[row][i] = 'Q';
- rec(row + 1);
- used.erase(i);
- board[row][i] = '.';
+ for (int i = 0; i < n; i++) {
+ if (!safe(row, i)) continue;
+ used.insert(i);
+ board[row][i] = 'Q';
+ rec(row + 1);
+ used.erase(i);
+ board[row][i] = '.';
+ }
}
- }
-public:
- int totalNQueens(int n) {
- this->n = n;
- board = vector<string>(n, string(n, '.'));
- rec(0);
- return res;
- }
+ public:
+ int totalNQueens(int n) {
+ this->n = n;
+ board = vector<string>(n, string(n, '.'));
+ rec(0);
+ return res;
+ }
};
diff --git a/Problems/0053.cpp b/Problems/0053.cpp
@@ -1,26 +1,27 @@
// memorization approach
class Solution {
-public:
- int maxSubArray(vector<int> &nums) {
- int n = nums.size(), maxi;
- vector<int> dp(n);
+ public:
+ int maxSubArray(vector<int> &nums) {
+ int n = nums.size(), maxi;
+ vector<int> dp(n);
- maxi = dp[0] = nums[0];
- for (int i = 1; i < n; i++) {
- dp[i] = nums[i] + max(dp[i - 1], 0);
- maxi = max(maxi, dp[i]);
+ maxi = dp[0] = nums[0];
+ for (int i = 1; i < n; i++) {
+ dp[i] = nums[i] + max(dp[i - 1], 0);
+ maxi = max(maxi, dp[i]);
+ }
+ return maxi;
}
- return maxi;
- }
};
// optimized, memorize only the previous value
class Solution {
-public:
- int maxSubArray(vector<int> &nums) {
- int n = nums.size(), maxi, prev;
- maxi = prev = nums[0];
- for (int i = 1; i < n; i++) maxi = max(maxi, prev = nums[i] + max(prev, 0));
- return maxi;
- }
+ public:
+ int maxSubArray(vector<int> &nums) {
+ int n = nums.size(), maxi, prev;
+ maxi = prev = nums[0];
+ for (int i = 1; i < n; i++)
+ maxi = max(maxi, prev = nums[i] + max(prev, 0));
+ return maxi;
+ }
};
diff --git a/Problems/0054.cpp b/Problems/0054.cpp
@@ -1,44 +1,37 @@
class Solution {
- pair<int, int> offset[4] = {
- { 0, 1},
- { 1, 0},
- { 0, -1},
- {-1, 0}
- };
- int limit_offset[4] = {1, -1, -1, 1};
- int limit[4] = {0, 0, 0, 0};
-
- int &m = limit[2], &n = limit[1];
-
- bool valid(int i, int j) {
- return i >= limit[0] && i <= m && j >= limit[3] && j <= n;
- }
-
-public:
- vector<int> spiralOrder(vector<vector<int>> &matrix) {
- vector<int> res;
- int direction = 0;
- int cnt = 0;
- int size;
- int i = 0, j = 0;
-
- m = matrix.size() - 1;
- n = matrix[0].size() - 1;
- size = (m + 1) * (n + 1);
-
- while (true) {
- res.push_back(matrix[i][j]);
- if (++cnt == size) break;
-
- if (!valid(i + offset[direction].first, j + offset[direction].second)) {
- limit[direction] += limit_offset[direction];
- direction = (direction + 1) % 4;
- }
-
- i += offset[direction].first;
- j += offset[direction].second;
- }
+ pair<int, int> offset[4] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
+ int limit_offset[4] = {1, -1, -1, 1};
+ int limit[4] = {0, 0, 0, 0};
+
+ int &m = limit[2], &n = limit[1];
+
+ bool valid(int i, int j) { return i >= limit[0] && i <= m && j >= limit[3] && j <= n; }
+
+ public:
+ vector<int> spiralOrder(vector<vector<int>> &matrix) {
+ vector<int> res;
+ int direction = 0;
+ int cnt = 0;
+ int size;
+ int i = 0, j = 0;
+
+ m = matrix.size() - 1;
+ n = matrix[0].size() - 1;
+ size = (m + 1) * (n + 1);
- return res;
- }
+ while (true) {
+ res.push_back(matrix[i][j]);
+ if (++cnt == size) break;
+
+ if (!valid(i + offset[direction].first, j + offset[direction].second)) {
+ limit[direction] += limit_offset[direction];
+ direction = (direction + 1) % 4;
+ }
+
+ i += offset[direction].first;
+ j += offset[direction].second;
+ }
+
+ return res;
+ }
};
diff --git a/Problems/0055.cpp b/Problems/0055.cpp
@@ -1,8 +1,9 @@
class Solution {
-public:
- bool canJump(vector<int> &nums) {
- int n = nums.size(), limit = 0;
- for (int i = 0; i <= limit && i < n; i++) limit = max(limit, i + nums[i]);
- return limit >= n - 1;
- }
+ public:
+ bool canJump(vector<int> &nums) {
+ int n = nums.size(), limit = 0;
+ for (int i = 0; i <= limit && i < n; i++)
+ limit = max(limit, i + nums[i]);
+ return limit >= n - 1;
+ }
};
diff --git a/Problems/0056.cpp b/Problems/0056.cpp
@@ -1,25 +1,23 @@
class Solution {
- typedef vector<int> interval;
+ typedef vector<int> interval;
-public:
- vector<interval> merge(vector<interval> &intervals) {
- auto cmp = [](const interval &i1, const interval &i2) {
- return i1[0] < i2[0];
- };
- sort(intervals.begin(), intervals.end(), cmp);
+ public:
+ vector<interval> merge(vector<interval> &intervals) {
+ auto cmp = [](const interval &i1, const interval &i2) { return i1[0] < i2[0]; };
+ sort(intervals.begin(), intervals.end(), cmp);
- vector<interval> res;
- int start = intervals[0][0], end = intervals[0][1];
- for (auto &i : intervals) {
- if (i[0] > end) {
- res.push_back({start, end});
- start = i[0];
- }
- end = max(end, i[1]);
- }
+ vector<interval> res;
+ int start = intervals[0][0], end = intervals[0][1];
+ for (auto &i : intervals) {
+ if (i[0] > end) {
+ res.push_back({start, end});
+ start = i[0];
+ }
+ end = max(end, i[1]);
+ }
- if (res.empty() || res.back()[1] != end) res.push_back({start, end});
+ if (res.empty() || res.back()[1] != end) res.push_back({start, end});
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0057.cpp b/Problems/0057.cpp
@@ -1,25 +1,27 @@
class Solution {
- typedef vector<int> Interval;
+ typedef vector<int> Interval;
-public:
- vector<Interval> insert(vector<Interval> &intervals, Interval &newInterval) {
- if (intervals.empty()) return {newInterval};
+ public:
+ vector<Interval> insert(vector<Interval> &intervals, Interval &newInterval) {
+ if (intervals.empty()) return {newInterval};
- vector<Interval> res;
- int n = intervals.size(), i = 0;
- for (; i < n && intervals[i][1] < newInterval[0]; i++) {
- res.push_back(intervals[i]);
- }
+ vector<Interval> res;
+ int n = intervals.size(), i = 0;
+ for (; i < n && intervals[i][1] < newInterval[0]; i++) {
+ res.push_back(intervals[i]);
+ }
- for (; i < n && newInterval[1] >= intervals[i][0]; i++) {
- newInterval[0] = min(newInterval[0], intervals[i][0]);
- newInterval[1] = max(newInterval[1], intervals[i][1]);
- }
+ for (; i < n && newInterval[1] >= intervals[i][0]; i++) {
+ newInterval[0] = min(newInterval[0], intervals[i][0]);
+ newInterval[1] = max(newInterval[1], intervals[i][1]);
+ }
- res.push_back(newInterval);
+ res.push_back(newInterval);
- for (; i < n; i++) { res.push_back(intervals[i]); }
+ for (; i < n; i++) {
+ res.push_back(intervals[i]);
+ }
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0058.cpp b/Problems/0058.cpp
@@ -1,10 +1,11 @@
class Solution {
-public:
- int lengthOfLastWord(string s) {
- int i = s.size(), res = 0;
- while (--i >= 0 && isspace(s[i]))
- ;
- while (i >= 0 && !isspace(s[i--])) res++;
- return res;
- }
+ public:
+ int lengthOfLastWord(string s) {
+ int i = s.size(), res = 0;
+ while (--i >= 0 && isspace(s[i]))
+ ;
+ while (i >= 0 && !isspace(s[i--]))
+ res++;
+ return res;
+ }
};
diff --git a/Problems/0059.cpp b/Problems/0059.cpp
@@ -1,43 +1,36 @@
class Solution {
- pair<int, int> offset[4] = {
- { 0, 1},
- { 1, 0},
- { 0, -1},
- {-1, 0}
- };
- int limit_offset[4] = {1, -1, -1, 1};
- int limit[4] = {0, 0, 0, 0};
-
- int &m = limit[2], &n = limit[1];
-
- bool valid(int i, int j) {
- return i >= limit[0] && i <= m && j >= limit[3] && j <= n;
- }
-
-public:
- vector<vector<int>> generateMatrix(int dim) {
- vector<vector<int>> res(dim, vector<int>(dim));
- int direction = 0;
- int cnt = 0;
- int size;
- int i = 0, j = 0;
-
- m = n = dim - 1;
- size = (m + 1) * (n + 1);
-
- while (true) {
- res[i][j] = ++cnt;
- if (cnt == size) break;
-
- if (!valid(i + offset[direction].first, j + offset[direction].second)) {
- limit[direction] += limit_offset[direction];
- direction = (direction + 1) % 4;
- }
-
- i += offset[direction].first;
- j += offset[direction].second;
- }
+ pair<int, int> offset[4] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
+ int limit_offset[4] = {1, -1, -1, 1};
+ int limit[4] = {0, 0, 0, 0};
+
+ int &m = limit[2], &n = limit[1];
+
+ bool valid(int i, int j) { return i >= limit[0] && i <= m && j >= limit[3] && j <= n; }
+
+ public:
+ vector<vector<int>> generateMatrix(int dim) {
+ vector<vector<int>> res(dim, vector<int>(dim));
+ int direction = 0;
+ int cnt = 0;
+ int size;
+ int i = 0, j = 0;
+
+ m = n = dim - 1;
+ size = (m + 1) * (n + 1);
- return res;
- }
+ while (true) {
+ res[i][j] = ++cnt;
+ if (cnt == size) break;
+
+ if (!valid(i + offset[direction].first, j + offset[direction].second)) {
+ limit[direction] += limit_offset[direction];
+ direction = (direction + 1) % 4;
+ }
+
+ i += offset[direction].first;
+ j += offset[direction].second;
+ }
+
+ return res;
+ }
};
diff --git a/Problems/0060.cpp b/Problems/0060.cpp
@@ -1,15 +1,17 @@
class Solution {
-public:
- string getPermutation(int n, int k) {
- vector<char> avail = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
- int factorial = 1, pos;
- string res;
- for (int i = 1; i <= n; i++) factorial *= i;
- for (k--; n; n--) {
- factorial /= n;
- res += avail[pos = k / factorial], k -= pos * factorial;
- for (int i = pos; i < avail.size() - 1; i++) avail[i] = avail[i + 1];
+ public:
+ string getPermutation(int n, int k) {
+ vector<char> avail = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
+ int factorial = 1, pos;
+ string res;
+ for (int i = 1; i <= n; i++)
+ factorial *= i;
+ for (k--; n; n--) {
+ factorial /= n;
+ res += avail[pos = k / factorial], k -= pos * factorial;
+ for (int i = pos; i < avail.size() - 1; i++)
+ avail[i] = avail[i + 1];
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0061.cpp b/Problems/0061.cpp
@@ -1,29 +1,29 @@
class Solution {
- int len(ListNode *head) {
- int count = 0;
- while (head) {
- count++;
- head = head->next;
+ int len(ListNode *head) {
+ int count = 0;
+ while (head) {
+ count++;
+ head = head->next;
+ }
+ return count;
}
- return count;
- }
-public:
- ListNode *rotateRight(ListNode *head, int k) {
- if (!head) return nullptr;
+ public:
+ ListNode *rotateRight(ListNode *head, int k) {
+ if (!head) return nullptr;
- k %= len(head);
- ListNode *p, *t;
- t = p = head;
- for (; p->next; p = p->next) {
- if (k)
- k--;
- else
- t = t->next;
+ k %= len(head);
+ ListNode *p, *t;
+ t = p = head;
+ for (; p->next; p = p->next) {
+ if (k)
+ k--;
+ else
+ t = t->next;
+ }
+ p->next = head;
+ head = t->next;
+ t->next = nullptr;
+ return head;
}
- p->next = head;
- head = t->next;
- t->next = nullptr;
- return head;
- }
};
diff --git a/Problems/0062.cpp b/Problems/0062.cpp
@@ -1,21 +1,21 @@
class Solution {
-public:
- int uniquePaths(int n, int m) {
- vector<vector<int>> mat(n, vector<int>(m, 0));
- queue<pair<int, int>> q;
- q.push({n - 1, m - 1}), mat[n - 1][m - 1] = 1;
- while (!q.empty()) {
- auto [x, y] = q.front();
- q.pop();
- if (x - 1 >= 0) {
- mat[x - 1][y] += mat[x][y];
- if (mat[x - 1][y] == mat[x][y]) q.push({x - 1, y});
- }
- if (y - 1 >= 0) {
- mat[x][y - 1] += mat[x][y];
- if (mat[x][y - 1] == mat[x][y]) q.push({x, y - 1});
- }
+ public:
+ int uniquePaths(int n, int m) {
+ vector<vector<int>> mat(n, vector<int>(m, 0));
+ queue<pair<int, int>> q;
+ q.push({n - 1, m - 1}), mat[n - 1][m - 1] = 1;
+ while (!q.empty()) {
+ auto [x, y] = q.front();
+ q.pop();
+ if (x - 1 >= 0) {
+ mat[x - 1][y] += mat[x][y];
+ if (mat[x - 1][y] == mat[x][y]) q.push({x - 1, y});
+ }
+ if (y - 1 >= 0) {
+ mat[x][y - 1] += mat[x][y];
+ if (mat[x][y - 1] == mat[x][y]) q.push({x, y - 1});
+ }
+ }
+ return mat[0][0];
}
- return mat[0][0];
- }
};
diff --git a/Problems/0063.cpp b/Problems/0063.cpp
@@ -1,28 +1,28 @@
class Solution {
-public:
- int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) {
- int dp[101][101] = {0};
- int n = obstacleGrid.size(), m = obstacleGrid[0].size();
+ public:
+ int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) {
+ int dp[101][101] = {0};
+ int n = obstacleGrid.size(), m = obstacleGrid[0].size();
- for (int i = 0, flag = 0; i < n; i++) {
- if (flag || obstacleGrid[i][0])
- flag = true;
- else
- dp[i][0] = 1;
- }
+ for (int i = 0, flag = 0; i < n; i++) {
+ if (flag || obstacleGrid[i][0])
+ flag = true;
+ else
+ dp[i][0] = 1;
+ }
- for (int i = 0, flag = 0; i < m; i++) {
- if (flag || obstacleGrid[0][i])
- flag = true;
- else
- dp[0][i] = 1;
- }
+ for (int i = 0, flag = 0; i < m; i++) {
+ if (flag || obstacleGrid[0][i])
+ flag = true;
+ else
+ dp[0][i] = 1;
+ }
- for (int i = 1; i < n; i++) {
- for (int j = 1; j < m; j++) {
- if (obstacleGrid[i][j] != 1) dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
- }
+ for (int i = 1; i < n; i++) {
+ for (int j = 1; j < m; j++) {
+ if (obstacleGrid[i][j] != 1) dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
+ }
+ }
+ return dp[n - 1][m - 1];
}
- return dp[n - 1][m - 1];
- }
};
diff --git a/Problems/0064.cpp b/Problems/0064.cpp
@@ -1,17 +1,19 @@
class Solution {
-public:
- int minPathSum(vector<vector<int>> &grid) {
- int n = grid.size(), m = grid[0].size();
+ public:
+ int minPathSum(vector<vector<int>> &grid) {
+ int n = grid.size(), m = grid[0].size();
- for (int i = 1; i < n; i++) grid[i][0] += grid[i - 1][0];
- for (int j = 1; j < m; j++) grid[0][j] += grid[0][j - 1];
+ for (int i = 1; i < n; i++)
+ grid[i][0] += grid[i - 1][0];
+ for (int j = 1; j < m; j++)
+ grid[0][j] += grid[0][j - 1];
- for (int i = 1; i < n; i++) {
- for (int j = 1; j < m; j++) {
- grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]);
- }
- }
+ for (int i = 1; i < n; i++) {
+ for (int j = 1; j < m; j++) {
+ grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]);
+ }
+ }
- return grid[n - 1][m - 1];
- }
+ return grid[n - 1][m - 1];
+ }
};
diff --git a/Problems/0066.cpp b/Problems/0066.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- vector<int> plusOne(vector<int> &digits) {
- vector<int> res;
+ public:
+ vector<int> plusOne(vector<int> &digits) {
+ vector<int> res;
- int add = 1;
- for (int i = digits.size() - 1; i >= 0 || add; i--) {
- if (i >= 0) add += digits[i];
- res.push_back(add % 10);
- add /= 10;
+ int add = 1;
+ for (int i = digits.size() - 1; i >= 0 || add; i--) {
+ if (i >= 0) add += digits[i];
+ res.push_back(add % 10);
+ add /= 10;
+ }
+ reverse(res.begin(), res.end());
+ return res;
}
- reverse(res.begin(), res.end());
- return res;
- }
};
diff --git a/Problems/0067.cpp b/Problems/0067.cpp
@@ -1,17 +1,17 @@
class Solution {
-public:
- string addBinary(string a, string b) {
- string res;
- int i = a.size() - 1;
- int j = b.size() - 1;
- int add = 0;
- while (i >= 0 || j >= 0 || add) {
- if (i >= 0) add += a[i--] - '0';
- if (j >= 0) add += b[j--] - '0';
- res += to_string(add % 2);
- add /= 2;
+ public:
+ string addBinary(string a, string b) {
+ string res;
+ int i = a.size() - 1;
+ int j = b.size() - 1;
+ int add = 0;
+ while (i >= 0 || j >= 0 || add) {
+ if (i >= 0) add += a[i--] - '0';
+ if (j >= 0) add += b[j--] - '0';
+ res += to_string(add % 2);
+ add /= 2;
+ }
+ reverse(res.begin(), res.end());
+ return res;
}
- reverse(res.begin(), res.end());
- return res;
- }
};
diff --git a/Problems/0068.cpp b/Problems/0068.cpp
@@ -1,36 +1,34 @@
class Solution {
-public:
- vector<string> fullJustify(vector<string> &words, int maxWidth) {
- vector<string> res;
- int i = 0, j;
- while (i < words.size()) {
- int count = words[i].size(); // character count
- for (j = i + 1; j < words.size() && count <= maxWidth; j++)
- count += words[j].size() + 1; // word lenght + at least 1 space
+ public:
+ vector<string> fullJustify(vector<string> &words, int maxWidth) {
+ vector<string> res;
+ int i = 0, j;
+ while (i < words.size()) {
+ int count = words[i].size(); // character count
+ for (j = i + 1; j < words.size() && count <= maxWidth; j++)
+ count += words[j].size() + 1; // word lenght + at least 1 space
- if (count > maxWidth)
- count -= words[--j].size() + 1; // if we overshot, remove last word
- int wordc = j - i; // number of words for the current row
- count -=
- wordc - 1; // remove minimum padding added from the character count;
- int white = maxWidth - count; // how much whitespace
- string row = words[i++];
- if (i != j) {
- if (j != words.size()) {
- while (i < j) {
- int segment = ceil((double)white / (wordc-- - 1));
- row += string(min(segment, white), ' ') + words[i++];
- white -= segment;
- }
- } else {
- // last row, adjust left
- while (i < j) row += " " + words[i++];
+ if (count > maxWidth) count -= words[--j].size() + 1; // if we overshot, remove last word
+ int wordc = j - i; // number of words for the current row
+ count -= wordc - 1; // remove minimum padding added from the character count;
+ int white = maxWidth - count; // how much whitespace
+ string row = words[i++];
+ if (i != j) {
+ if (j != words.size()) {
+ while (i < j) {
+ int segment = ceil((double)white / (wordc-- - 1));
+ row += string(min(segment, white), ' ') + words[i++];
+ white -= segment;
+ }
+ } else {
+ // last row, adjust left
+ while (i < j)
+ row += " " + words[i++];
+ }
+ }
+ row += string(maxWidth - row.size(), ' '); // padd the remainder of the row
+ res.push_back(row); // push the current row to the result
}
- }
- row +=
- string(maxWidth - row.size(), ' '); // padd the remainder of the row
- res.push_back(row); // push the current row to the result
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0069.cpp b/Problems/0069.cpp
@@ -1,16 +1,16 @@
class Solution {
-public:
- int mySqrt(int x) {
- int low = 1, high = x;
- while (low <= high) {
- int mid = low + (high - low) / 2;
- if (mid == x / mid)
- return mid;
- else if (mid > x / mid)
- high = mid - 1;
- else
- low = mid + 1;
+ public:
+ int mySqrt(int x) {
+ int low = 1, high = x;
+ while (low <= high) {
+ int mid = low + (high - low) / 2;
+ if (mid == x / mid)
+ return mid;
+ else if (mid > x / mid)
+ high = mid - 1;
+ else
+ low = mid + 1;
+ }
+ return high;
}
- return high;
- }
};
diff --git a/Problems/0070.cpp b/Problems/0070.cpp
@@ -1,27 +1,28 @@
// memorization approach
class Solution {
-public:
- int climbStairs(int n) {
- vector<int> vec(46);
- vec[0] = 1;
- vec[1] = 1;
- for (int i = 2; i <= n; i++) vec[i] = vec[i - 1] + vec[i - 2];
+ public:
+ int climbStairs(int n) {
+ vector<int> vec(46);
+ vec[0] = 1;
+ vec[1] = 1;
+ for (int i = 2; i <= n; i++)
+ vec[i] = vec[i - 1] + vec[i - 2];
- return vec[n];
- }
+ return vec[n];
+ }
}
// optimized, memorize only the previous two values
class Solution {
-public:
- int climbStairs(int n) {
- int first = 1, second = 1;
- for (int i = 2; i <= n; i++) {
- int cnt = first + second;
- first = second;
- second = cnt;
- }
+ public:
+ int climbStairs(int n) {
+ int first = 1, second = 1;
+ for (int i = 2; i <= n; i++) {
+ int cnt = first + second;
+ first = second;
+ second = cnt;
+ }
- return second;
- }
+ return second;
+ }
};
diff --git a/Problems/0071.cpp b/Problems/0071.cpp
@@ -1,26 +1,28 @@
class Solution {
-public:
+ public:
string simplifyPath(string path) {
- deque<string> dq;
- int start = 0;
+ deque<string> dq;
+ int start = 0;
- path.push_back('/');
- for(int i=0; i<path.size(); i++) {
- if(path[i] != '/') continue;
- else {
- string s = path.substr(start, i - start);
- if(s=="..") {
- if(!dq.empty()) dq.pop_back();
- }else if(!s.empty() && s!=".") dq.push_back(s);
- start = i + 1;
+ path.push_back('/');
+ for (int i = 0; i < path.size(); i++) {
+ if (path[i] != '/')
+ continue;
+ else {
+ string s = path.substr(start, i - start);
+ if (s == "..") {
+ if (!dq.empty()) dq.pop_back();
+ } else if (!s.empty() && s != ".")
+ dq.push_back(s);
+ start = i + 1;
+ }
}
- }
- string res = "";
- while(!dq.empty()) {
- res+="/" + dq.front();
- dq.pop_front();
- }
- return res.empty() ? "/" : res;
+ string res = "";
+ while (!dq.empty()) {
+ res += "/" + dq.front();
+ dq.pop_front();
+ }
+ return res.empty() ? "/" : res;
}
-};
+};
diff --git a/Problems/0072.cpp b/Problems/0072.cpp
@@ -1,41 +1,43 @@
class Solution {
-public:
- int minDistance(string word1, string word2) {
- int n = word1.size(), m = word2.size();
- vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
- for (int i = 1; i <= n; i++) dp[i][0] = i;
- for (int j = 1; j <= m; j++) dp[0][j] = j;
+ public:
+ int minDistance(string word1, string word2) {
+ int n = word1.size(), m = word2.size();
+ vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
+ for (int i = 1; i <= n; i++)
+ dp[i][0] = i;
+ for (int j = 1; j <= m; j++)
+ dp[0][j] = j;
- for (int i = 1; i <= n; i++) {
- for (int j = 1; j <= m; j++) {
- if (word1[i - 1] == word2[j - 1])
- dp[i][j] = dp[i - 1][j - 1];
- else
- dp[i][j] = min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])) + 1;
- }
+ for (int i = 1; i <= n; i++) {
+ for (int j = 1; j <= m; j++) {
+ if (word1[i - 1] == word2[j - 1])
+ dp[i][j] = dp[i - 1][j - 1];
+ else
+ dp[i][j] = min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])) + 1;
+ }
+ }
+ return dp.back().back();
}
- return dp.back().back();
- }
};
// Improvement, use two DP arrays instead of a matrix
class Solution {
-public:
- int minDistance(const string &word1, const string &word2) {
- int n = word1.size(), m = word2.size();
- if (n == 0 || m == 0) return max(m, n);
- vector<int> dp1(m + 1, 0), dp2(m + 1, 0);
- iota(dp1.begin(), dp1.end(), 0);
- for (int i = 1; i <= n; i++) {
- dp2[0]++;
- for (int j = 1; j <= m; j++) {
- if (word1[i - 1] == word2[j - 1])
- dp2[j] = dp1[j - 1];
- else
- dp2[j] = min({dp1[j - 1], dp2[j - 1], dp1[j]}) + 1;
- }
- dp1 = dp2;
+ public:
+ int minDistance(const string &word1, const string &word2) {
+ int n = word1.size(), m = word2.size();
+ if (n == 0 || m == 0) return max(m, n);
+ vector<int> dp1(m + 1, 0), dp2(m + 1, 0);
+ iota(dp1.begin(), dp1.end(), 0);
+ for (int i = 1; i <= n; i++) {
+ dp2[0]++;
+ for (int j = 1; j <= m; j++) {
+ if (word1[i - 1] == word2[j - 1])
+ dp2[j] = dp1[j - 1];
+ else
+ dp2[j] = min({dp1[j - 1], dp2[j - 1], dp1[j]}) + 1;
+ }
+ dp1 = dp2;
+ }
+ return dp2[m];
}
- return dp2[m];
- }
};
diff --git a/Problems/0073.cpp b/Problems/0073.cpp
@@ -1,25 +1,27 @@
class Solution {
-public:
- void setZeroes(vector<vector<int>> &matrix) {
- int n = matrix.size(), m = matrix[0].size();
- unordered_set<int> rows, cols;
+ public:
+ void setZeroes(vector<vector<int>> &matrix) {
+ int n = matrix.size(), m = matrix[0].size();
+ unordered_set<int> rows, cols;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < m; j++) {
- if (matrix[i][j]) continue;
- rows.insert(i);
- cols.insert(j);
- }
- }
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < m; j++) {
+ if (matrix[i][j]) continue;
+ rows.insert(i);
+ cols.insert(j);
+ }
+ }
- for (int row : rows) {
- for (int j = 0; j < m; j++) matrix[row][j] = 0;
- }
+ for (int row : rows) {
+ for (int j = 0; j < m; j++)
+ matrix[row][j] = 0;
+ }
- for (int col : cols) {
- for (int i = 0; i < n; i++) matrix[i][col] = 0;
- }
+ for (int col : cols) {
+ for (int i = 0; i < n; i++)
+ matrix[i][col] = 0;
+ }
- return;
- }
+ return;
+ }
};
diff --git a/Problems/0074.cpp b/Problems/0074.cpp
@@ -1,59 +1,60 @@
class Solution {
-public:
- bool searchMatrix(vector<vector<int>> &matrix, int target) {
- int n = matrix.size(), m = matrix[0].size(), row = n - 1;
- for (int i = 0; i < n - 1; i++) {
- if (matrix[i + 1][0] > target) {
- row = i;
- break;
- }
- }
+ public:
+ bool searchMatrix(vector<vector<int>> &matrix, int target) {
+ int n = matrix.size(), m = matrix[0].size(), row = n - 1;
+ for (int i = 0; i < n - 1; i++) {
+ if (matrix[i + 1][0] > target) {
+ row = i;
+ break;
+ }
+ }
- int low = 0, high = m - 1;
- while (low <= high) {
- int mid = low + (high - low) / 2;
- if (matrix[row][mid] == target)
- return true;
- else if (matrix[row][mid] < target)
- low = mid + 1;
- else
- high = mid - 1;
+ int low = 0, high = m - 1;
+ while (low <= high) {
+ int mid = low + (high - low) / 2;
+ if (matrix[row][mid] == target)
+ return true;
+ else if (matrix[row][mid] < target)
+ low = mid + 1;
+ else
+ high = mid - 1;
+ }
+ return false;
}
- return false;
- }
};
// Treat the matrix as a sorted list
class Solution {
-public:
- bool searchMatrix(vector<vector<int>> &matrix, int target) {
- int n = matrix.size(), m = matrix[0].size();
- int low = 0, high = m * n - 1;
- while (low <= high) {
- int mid = low + (high - low) / 2;
- if (matrix[mid / m][mid % m] == target) return true;
- if (matrix[mid / m][mid % m] < target)
- low = mid + 1;
- else
- high = mid - 1;
+ public:
+ bool searchMatrix(vector<vector<int>> &matrix, int target) {
+ int n = matrix.size(), m = matrix[0].size();
+ int low = 0, high = m * n - 1;
+ while (low <= high) {
+ int mid = low + (high - low) / 2;
+ if (matrix[mid / m][mid % m] == target) return true;
+ if (matrix[mid / m][mid % m] < target)
+ low = mid + 1;
+ else
+ high = mid - 1;
+ }
+ return false;
}
- return false;
- }
};
// Binary Search Tree
class Solution {
-public:
- bool searchMatrix(vector<vector<int>> &matrix, int target) {
- int n = matrix.size(), m = matrix[0].size();
- int row = 0, col = m - 1;
-
- while (row < n && col > -1) {
- if (matrix[row][col] == target) return true;
- if (target > matrix[row][col]) row++;
- else col--;
+ public:
+ bool searchMatrix(vector<vector<int>> &matrix, int target) {
+ int n = matrix.size(), m = matrix[0].size();
+ int row = 0, col = m - 1;
+
+ while (row < n && col > -1) {
+ if (matrix[row][col] == target) return true;
+ if (target > matrix[row][col])
+ row++;
+ else
+ col--;
+ }
+ return false;
}
- return false;
- }
};
-
diff --git a/Problems/0075.cpp b/Problems/0075.cpp
@@ -1,10 +1,12 @@
class Solution {
-public:
- void sortColors(vector<int> &nums) {
- array<int, 3> arr;
- for (int n : nums) arr[n]++;
- int count = 0;
- for (int i = 0; i < 3; i++)
- while (arr[i]--) nums[count++] = i;
- }
+ public:
+ void sortColors(vector<int> &nums) {
+ array<int, 3> arr;
+ for (int n : nums)
+ arr[n]++;
+ int count = 0;
+ for (int i = 0; i < 3; i++)
+ while (arr[i]--)
+ nums[count++] = i;
+ }
};
diff --git a/Problems/0076.cpp b/Problems/0076.cpp
@@ -1,23 +1,24 @@
class Solution {
-public:
- string minWindow(string s, string t) {
- vector<int> remaining(128, 0);
- for (char c : t) remaining[c]++;
+ public:
+ string minWindow(string s, string t) {
+ vector<int> remaining(128, 0);
+ for (char c : t)
+ remaining[c]++;
- int required = t.size();
- int min = INT_MAX, start = 0, left = 0, i = 0;
- while (i <= s.size() && start < s.size()) {
- if (required) {
- if (i == s.size()) break;
- if (--remaining[s[i++]] >= 0) required--;
- } else {
- if (i - start < min) {
- min = i - start;
- left = start;
+ int required = t.size();
+ int min = INT_MAX, start = 0, left = 0, i = 0;
+ while (i <= s.size() && start < s.size()) {
+ if (required) {
+ if (i == s.size()) break;
+ if (--remaining[s[i++]] >= 0) required--;
+ } else {
+ if (i - start < min) {
+ min = i - start;
+ left = start;
+ }
+ if (++remaining[s[start++]] > 0) required++;
+ }
}
- if (++remaining[s[start++]] > 0) required++;
- }
+ return min == INT_MAX ? "" : s.substr(left, min);
}
- return min == INT_MAX ? "" : s.substr(left, min);
- }
};
diff --git a/Problems/0077.cpp b/Problems/0077.cpp
@@ -1,69 +1,69 @@
// Recursive solution
class Solution {
- vector<int> crnt;
- vector<vector<int>> res;
- void rec(int s, int n, int k) {
- if (s > n + 1) return;
- if (!k) {
- res.push_back(crnt);
- return;
- }
+ vector<int> crnt;
+ vector<vector<int>> res;
+ void rec(int s, int n, int k) {
+ if (s > n + 1) return;
+ if (!k) {
+ res.push_back(crnt);
+ return;
+ }
- crnt.push_back(s);
- rec(s + 1, n, k - 1);
- crnt.pop_back();
- rec(s + 1, n, k);
- }
+ crnt.push_back(s);
+ rec(s + 1, n, k - 1);
+ crnt.pop_back();
+ rec(s + 1, n, k);
+ }
-public:
- vector<vector<int>> combine(int n, int k) {
- rec(1, n, k);
- return res;
- }
+ public:
+ vector<vector<int>> combine(int n, int k) {
+ rec(1, n, k);
+ return res;
+ }
};
// Iterative solution
class Solution {
-public:
- vector<vector<int>> combine(int n, int k) {
- vector<vector<int>> res;
- vector<int> iter;
- iter.reserve(k);
- for (int mask = (1 << k) - 1; mask < 1 << n; mask++) {
- if (__builtin_popcount(mask) != k) continue;
+ public:
+ vector<vector<int>> combine(int n, int k) {
+ vector<vector<int>> res;
+ vector<int> iter;
+ iter.reserve(k);
+ for (int mask = (1 << k) - 1; mask < 1 << n; mask++) {
+ if (__builtin_popcount(mask) != k) continue;
- for (int crnt = mask, idx; crnt; crnt ^= 1 << (idx - 1)) {
- idx = __builtin_ffs(crnt);
- iter.push_back(idx);
- }
- res.push_back(iter);
- iter.clear();
+ for (int crnt = mask, idx; crnt; crnt ^= 1 << (idx - 1)) {
+ idx = __builtin_ffs(crnt);
+ iter.push_back(idx);
+ }
+ res.push_back(iter);
+ iter.clear();
+ }
+ return res;
}
- return res;
- }
};
// Improved iterative solution with bit twiddling
class Solution {
- int twiddle(int v) {
- int t = v | (v - 1);
- int w = (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctz(v) + 1));
- return w;
- }
+ int twiddle(int v) {
+ int t = v | (v - 1);
+ int w = (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctz(v) + 1));
+ return w;
+ }
-public:
- vector<vector<int>> combine(int n, int k) {
- vector<vector<int>> res;
- vector<int> iter;
- iter.reserve(k);
- for (int mask = (1 << k) - 1; mask < 1 << n; mask = twiddle(mask)) {
- for (int crnt = mask, idx; crnt; crnt ^= 1 << (idx - 1)) {
- idx = __builtin_ffs(crnt);
- iter.push_back(idx);
- }
- res.push_back(iter);
- iter.clear();
+ public:
+ vector<vector<int>> combine(int n, int k) {
+ vector<vector<int>> res;
+ vector<int> iter;
+ iter.reserve(k);
+ for (int mask = (1 << k) - 1; mask < 1 << n; mask = twiddle(mask)) {
+ for (int crnt = mask, idx; crnt; crnt ^= 1 << (idx - 1)) {
+ idx = __builtin_ffs(crnt);
+ iter.push_back(idx);
+ }
+ res.push_back(iter);
+ iter.clear();
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0078.cpp b/Problems/0078.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- vector<vector<int>> subsets(vector<int> &nums) {
- vector<vector<int>> res;
+ public:
+ vector<vector<int>> subsets(vector<int> &nums) {
+ vector<vector<int>> res;
- res.push_back({});
- for (int num : nums) {
- for (int i = res.size() - 1; i >= 0; i--) {
- res.push_back(res[i]);
- res.back().push_back(num);
- }
+ res.push_back({});
+ for (int num : nums) {
+ for (int i = res.size() - 1; i >= 0; i--) {
+ res.push_back(res[i]);
+ res.back().push_back(num);
+ }
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0079.cpp b/Problems/0079.cpp
@@ -1,45 +1,40 @@
class Solution {
- typedef vector<vector<char>> Matrix;
- typedef vector<vector<bool>> Marked;
- const vector<pair<int, int>> offsets = {
- { 0, 1},
- { 0, -1},
- { 1, 0},
- {-1, 0}
- };
-
- int n, m;
- int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }
-
- string word;
- bool dfs(const Matrix &mat, Marked &mark, int a, int b, int got) {
- if (got == word.size()) return true;
-
- mark[a][b] = true;
- for (auto [oa, ob] : offsets) {
- int x = a + oa, y = b + ob;
- if (!valid(x, y) || mark[x][y] || mat[x][y] != word[got]) continue;
- if (dfs(mat, mark, x, y, got + 1)) return true;
+ typedef vector<vector<char>> Matrix;
+ typedef vector<vector<bool>> Marked;
+ const vector<pair<int, int>> offsets = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
+
+ int n, m;
+ int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }
+
+ string word;
+ bool dfs(const Matrix &mat, Marked &mark, int a, int b, int got) {
+ if (got == word.size()) return true;
+
+ mark[a][b] = true;
+ for (auto [oa, ob] : offsets) {
+ int x = a + oa, y = b + ob;
+ if (!valid(x, y) || mark[x][y] || mat[x][y] != word[got]) continue;
+ if (dfs(mat, mark, x, y, got + 1)) return true;
+ }
+ mark[a][b] = false;
+
+ return false;
}
- mark[a][b] = false;
- return false;
- }
+ public:
+ bool exist(const Matrix &board, string word) {
+ n = board.size(), m = board[0].size();
+ this->word = word;
-public:
- bool exist(const Matrix &board, string word) {
- n = board.size(), m = board[0].size();
- this->word = word;
+ Marked visited(n, vector<bool>(m, false));
- Marked visited(n, vector<bool>(m, false));
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < m; j++) {
+ if (board[i][j] != word[0]) continue;
+ if (dfs(board, visited, i, j, 1)) return true;
+ }
+ }
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < m; j++) {
- if (board[i][j] != word[0]) continue;
- if (dfs(board, visited, i, j, 1)) return true;
- }
+ return false;
}
-
- return false;
- }
};
diff --git a/Problems/0080.cpp b/Problems/0080.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- int removeDuplicates(vector<int> &nums) {
- int k = 1;
- for (int i = 1; i < nums.size(); i++) {
- nums[k++] = nums[i];
- if (nums[i] == nums[i - 1]) {
- while (++i < nums.size() && nums[i] == nums[k - 2])
- ;
- i--;
- }
+ public:
+ int removeDuplicates(vector<int> &nums) {
+ int k = 1;
+ for (int i = 1; i < nums.size(); i++) {
+ nums[k++] = nums[i];
+ if (nums[i] == nums[i - 1]) {
+ while (++i < nums.size() && nums[i] == nums[k - 2])
+ ;
+ i--;
+ }
+ }
+ return k;
}
- return k;
- }
};
diff --git a/Problems/0081.cpp b/Problems/0081.cpp
@@ -1,24 +1,24 @@
class Solution {
-public:
- bool search(const vector<int> &nums, int target) {
- int left = 0, right = nums.size() - 1;
- while (left <= right) {
- int mid = left + (right - left) / 2;
- if (nums[mid] == target) return true;
- if (nums[mid] == nums[left]) {
- left++;
- continue;
- }
+ public:
+ bool search(const vector<int> &nums, int target) {
+ int left = 0, right = nums.size() - 1;
+ while (left <= right) {
+ int mid = left + (right - left) / 2;
+ if (nums[mid] == target) return true;
+ if (nums[mid] == nums[left]) {
+ left++;
+ continue;
+ }
- bool pivotArr = nums[left] <= nums[mid];
- bool targetArr = nums[left] <= target;
- if ((pivotArr ^ targetArr) ? (pivotArr) : (nums[mid] < target)) {
- left = mid + 1;
- } else {
- right = mid - 1;
- }
- }
+ bool pivotArr = nums[left] <= nums[mid];
+ bool targetArr = nums[left] <= target;
+ if ((pivotArr ^ targetArr) ? (pivotArr) : (nums[mid] < target)) {
+ left = mid + 1;
+ } else {
+ right = mid - 1;
+ }
+ }
- return false;
- }
+ return false;
+ }
};
diff --git a/Problems/0082.cpp b/Problems/0082.cpp
@@ -1,17 +1,18 @@
class Solution {
-public:
- ListNode *deleteDuplicates(ListNode *head) {
- ListNode top(-200, head);
+ public:
+ ListNode *deleteDuplicates(ListNode *head) {
+ ListNode top(-200, head);
- for (ListNode *p = &top, *c = head; c && c->next; c = c->next) {
- if (c->val == c->next->val) {
- while (c && c->next && c->val == c->next->val) c = c->next;
- p->next = c->next;
- if (!c) break;
- } else
- p = p->next;
- }
+ for (ListNode *p = &top, *c = head; c && c->next; c = c->next) {
+ if (c->val == c->next->val) {
+ while (c && c->next && c->val == c->next->val)
+ c = c->next;
+ p->next = c->next;
+ if (!c) break;
+ } else
+ p = p->next;
+ }
- return top.next;
- }
+ return top.next;
+ }
};
diff --git a/Problems/0083.cpp b/Problems/0083.cpp
@@ -1,12 +1,12 @@
class Solution {
-public:
- ListNode *deleteDuplicates(ListNode *head) {
- if (!head) return nullptr;
- for (ListNode *p = head; p->next;)
- if (p->val == p->next->val)
- p->next = p->next->next;
- else
- p = p->next;
- return head;
- }
+ public:
+ ListNode *deleteDuplicates(ListNode *head) {
+ if (!head) return nullptr;
+ for (ListNode *p = head; p->next;)
+ if (p->val == p->next->val)
+ p->next = p->next->next;
+ else
+ p = p->next;
+ return head;
+ }
};
diff --git a/Problems/0084.cpp b/Problems/0084.cpp
@@ -1,31 +1,31 @@
class Solution {
-public:
- int largestRectangleArea(vector<int> &heights) {
- int n = heights.size();
- vector<int> left(n), right(n);
- stack<int> st;
+ public:
+ int largestRectangleArea(vector<int> &heights) {
+ int n = heights.size();
+ vector<int> left(n), right(n);
+ stack<int> st;
- for (int i = 0; i < n; i++) {
- left[i] = i;
- while (!st.empty() && heights[st.top()] >= heights[i]) {
- left[i] = left[st.top()];
- st.pop();
- };
- st.push(i);
- }
+ for (int i = 0; i < n; i++) {
+ left[i] = i;
+ while (!st.empty() && heights[st.top()] >= heights[i]) {
+ left[i] = left[st.top()];
+ st.pop();
+ };
+ st.push(i);
+ }
- for (int i = n - 1; i >= 0; i--) {
- right[i] = i;
- while (!st.empty() && heights[st.top()] >= heights[i]) {
- right[i] = right[st.top()];
- st.pop();
- };
- st.push(i);
- }
+ for (int i = n - 1; i >= 0; i--) {
+ right[i] = i;
+ while (!st.empty() && heights[st.top()] >= heights[i]) {
+ right[i] = right[st.top()];
+ st.pop();
+ };
+ st.push(i);
+ }
- int res = 0;
- for (int i = 0; i < n; i++)
- res = max(res, (right[i] - left[i] + 1) * heights[i]);
- return res;
- }
+ int res = 0;
+ for (int i = 0; i < n; i++)
+ res = max(res, (right[i] - left[i] + 1) * heights[i]);
+ return res;
+ }
};
diff --git a/Problems/0086.cpp b/Problems/0086.cpp
@@ -1,18 +1,18 @@
class Solution {
-public:
- ListNode *partition(ListNode *head, int x) {
- ListNode hless, hmore;
- ListNode *less = &hless, *more = &hmore;
+ public:
+ ListNode *partition(ListNode *head, int x) {
+ ListNode hless, hmore;
+ ListNode *less = &hless, *more = &hmore;
- for (ListNode *crnt = head; crnt; crnt = crnt->next) {
- if (crnt->val < x)
- less = less->next = crnt;
- else
- more = more->next = crnt;
- }
+ for (ListNode *crnt = head; crnt; crnt = crnt->next) {
+ if (crnt->val < x)
+ less = less->next = crnt;
+ else
+ more = more->next = crnt;
+ }
- less->next = hmore.next;
- more->next = nullptr;
- return hless.next;
- }
+ less->next = hmore.next;
+ more->next = nullptr;
+ return hless.next;
+ }
};
diff --git a/Problems/0087.cpp b/Problems/0087.cpp
@@ -1,29 +1,29 @@
class Solution {
- unordered_map<string, bool> um;
+ unordered_map<string, bool> um;
-public:
- bool isScramble(string s1, string s2) {
- if (um.count(s1 + s2)) return um[s1 + s2];
- if (s1.size() != s2.size()) return false;
- if (s1 == s2) return true;
+ public:
+ bool isScramble(string s1, string s2) {
+ if (um.count(s1 + s2)) return um[s1 + s2];
+ if (s1.size() != s2.size()) return false;
+ if (s1 == s2) return true;
- vector<int> count(128, 0);
- int n = s1.size();
- um[s1 + s2] = false;
+ vector<int> count(128, 0);
+ int n = s1.size();
+ um[s1 + s2] = false;
- for (int i = 0; i < n; i++) count[s1[i]]++, count[s2[i]]--;
- for (int n : count)
- if (n) return false;
+ for (int i = 0; i < n; i++)
+ count[s1[i]]++, count[s2[i]]--;
+ for (int n : count)
+ if (n) return false;
- for (int k = 1; k < n; k++) {
- if (isScramble(s1.substr(0, k), s2.substr(0, k)) &&
- isScramble(s1.substr(k), s2.substr(k)) ||
- isScramble(s1.substr(0, k), s2.substr(n - k)) &&
- isScramble(s1.substr(k), s2.substr(0, n - k))) {
- um[s1 + s2] = true;
- return true;
- }
+ for (int k = 1; k < n; k++) {
+ if (isScramble(s1.substr(0, k), s2.substr(0, k)) && isScramble(s1.substr(k), s2.substr(k)) ||
+ isScramble(s1.substr(0, k), s2.substr(n - k)) &&
+ isScramble(s1.substr(k), s2.substr(0, n - k))) {
+ um[s1 + s2] = true;
+ return true;
+ }
+ }
+ return false;
}
- return false;
- }
};
diff --git a/Problems/0088.cpp b/Problems/0088.cpp
@@ -1,10 +1,11 @@
class Solution {
-public:
- void merge(vector<int> &nums1, int m, vector<int> &nums2, int n) {
- int i = m - 1, j = n - 1, k = m + n - 1;
+ public:
+ void merge(vector<int> &nums1, int m, vector<int> &nums2, int n) {
+ int i = m - 1, j = n - 1, k = m + n - 1;
- while (i >= 0 && j >= 0)
- nums1[k--] = nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
- while (j >= 0) nums1[k--] = nums2[j--];
- }
+ while (i >= 0 && j >= 0)
+ nums1[k--] = nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
+ while (j >= 0)
+ nums1[k--] = nums2[j--];
+ }
};
diff --git a/Problems/0090.cpp b/Problems/0090.cpp
@@ -1,19 +1,19 @@
class Solution {
-public:
- vector<vector<int>> subsetsWithDup(vector<int> &nums) {
- sort(nums.begin(), nums.end());
- vector<vector<int>> res = {{}, {nums[0]}};
+ public:
+ vector<vector<int>> subsetsWithDup(vector<int> &nums) {
+ sort(nums.begin(), nums.end());
+ vector<vector<int>> res = {{}, {nums[0]}};
- int prev = 1;
- for (int i = 1; i < nums.size(); i++) {
- int end = nums[i] == nums[i - 1] ? prev : 0;
- prev = res.size();
- for (int j = res.size() - 1; j >= end; j--) {
- res.push_back(res[j]);
- res.back().push_back(nums[i]);
- }
- }
+ int prev = 1;
+ for (int i = 1; i < nums.size(); i++) {
+ int end = nums[i] == nums[i - 1] ? prev : 0;
+ prev = res.size();
+ for (int j = res.size() - 1; j >= end; j--) {
+ res.push_back(res[j]);
+ res.back().push_back(nums[i]);
+ }
+ }
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0091.cpp b/Problems/0091.cpp
@@ -1,2 +1 @@
-Formating: Problems/0091.cpp
-Formating: Problems/0413.cpp
+Formating : Problems / 0091.cpp Formating : Problems / 0413.cpp
diff --git a/Problems/0092.cpp b/Problems/0092.cpp
@@ -1,20 +1,21 @@
class Solution {
-public:
- ListNode *reverseBetween(ListNode *head, int left, int right) {
- ListNode top;
- top.next = head;
- ListNode *prev = ⊤
+ public:
+ ListNode *reverseBetween(ListNode *head, int left, int right) {
+ ListNode top;
+ top.next = head;
+ ListNode *prev = ⊤
- for (int i = 1; i < left; i++) prev = prev->next;
+ for (int i = 1; i < left; i++)
+ prev = prev->next;
- ListNode *crnt = prev->next;
- for (int i = 0; i < right - left; i++) {
- ListNode *tmp = prev->next;
- prev->next = crnt->next;
- crnt->next = crnt->next->next;
- prev->next->next = tmp;
- }
+ ListNode *crnt = prev->next;
+ for (int i = 0; i < right - left; i++) {
+ ListNode *tmp = prev->next;
+ prev->next = crnt->next;
+ crnt->next = crnt->next->next;
+ prev->next->next = tmp;
+ }
- return top.next;
- }
+ return top.next;
+ }
};
diff --git a/Problems/0093.cpp b/Problems/0093.cpp
@@ -1,42 +1,41 @@
class Solution {
- bool valid(const string &s) {
- if (s.empty()) return true;
- return stoi(s) >= 0 && stoi(s) <= 255;
- }
+ bool valid(const string &s) {
+ if (s.empty()) return true;
+ return stoi(s) >= 0 && stoi(s) <= 255;
+ }
-public:
- vector<string> restoreIpAddresses(string s) {
- int n = s.size();
+ public:
+ vector<string> restoreIpAddresses(string s) {
+ int n = s.size();
- vector<string> res;
- string s1, s2, s3, s4;
- bool e4;
+ vector<string> res;
+ string s1, s2, s3, s4;
+ bool e4;
- s1 = "";
- for (int i = 0; i < n; i++) {
- s1 += s[i], s2 = "";
- if (!valid(s1)) break;
- for (int j = i + 1; j < n; j++) {
- s2 += s[j], s3 = "";
- if (!valid(s2)) break;
- for (int k = j + 1; k < n; k++) {
- s3 += s[k], s4 = "";
- if (!valid(s3)) break;
- for (int l = k + 1; l < n; l++) {
- s4 += s[l], e4 = false;
- if (!valid(s4) || (s4.size() >= 2 && s4.front() == '0')) {
- e4 = true;
- break;
+ s1 = "";
+ for (int i = 0; i < n; i++) {
+ s1 += s[i], s2 = "";
+ if (!valid(s1)) break;
+ for (int j = i + 1; j < n; j++) {
+ s2 += s[j], s3 = "";
+ if (!valid(s2)) break;
+ for (int k = j + 1; k < n; k++) {
+ s3 += s[k], s4 = "";
+ if (!valid(s3)) break;
+ for (int l = k + 1; l < n; l++) {
+ s4 += s[l], e4 = false;
+ if (!valid(s4) || (s4.size() >= 2 && s4.front() == '0')) {
+ e4 = true;
+ break;
+ }
+ }
+ if (!e4 && !s4.empty()) res.push_back(s1 + "." + s2 + "." + s3 + "." + s4);
+ if (s3.front() == '0') break;
+ }
+ if (s2.front() == '0') break;
}
- }
- if (!e4 && !s4.empty())
- res.push_back(s1 + "." + s2 + "." + s3 + "." + s4);
- if (s3.front() == '0') break;
+ if (s1.front() == '0') break;
}
- if (s2.front() == '0') break;
- }
- if (s1.front() == '0') break;
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0094.cpp b/Problems/0094.cpp
@@ -1,24 +1,24 @@
class Solution {
-public:
- vector<int> inorderTraversal(TreeNode *root) {
- vector<int> res;
- stack<TreeNode *> st;
+ public:
+ vector<int> inorderTraversal(TreeNode *root) {
+ vector<int> res;
+ stack<TreeNode *> st;
- while (true) {
- while (root) {
- st.push(root);
- root = root->left;
- }
+ while (true) {
+ while (root) {
+ st.push(root);
+ root = root->left;
+ }
+
+ if (!st.empty()) {
+ root = st.top();
+ st.pop();
+ res.push_back(root->val);
+ root = root->right;
+ } else
+ return res;
+ }
- if (!st.empty()) {
- root = st.top();
- st.pop();
- res.push_back(root->val);
- root = root->right;
- } else
return res;
}
-
- return res;
- }
};
diff --git a/Problems/0095.cpp b/Problems/0095.cpp
@@ -1,21 +1,21 @@
class Solution {
- vector<TreeNode *> dp[10][10];
+ vector<TreeNode *> dp[10][10];
- vector<TreeNode *> rec(int n, int left, int right) {
- vector<TreeNode *> &res = dp[left][right];
- if (!res.empty()) return res;
+ vector<TreeNode *> rec(int n, int left, int right) {
+ vector<TreeNode *> &res = dp[left][right];
+ if (!res.empty()) return res;
- for (int i = left; i <= right; i++) {
- for (const auto &l : rec(n, left, i - 1)) {
- for (const auto &r : rec(n, i + 1, right)) {
- res.push_back(new TreeNode(i, l, r));
+ for (int i = left; i <= right; i++) {
+ for (const auto &l : rec(n, left, i - 1)) {
+ for (const auto &r : rec(n, i + 1, right)) {
+ res.push_back(new TreeNode(i, l, r));
+ }
+ }
}
- }
+ if (res.empty()) return {nullptr};
+ return res;
}
- if (res.empty()) return {nullptr};
- return res;
- }
-public:
- vector<TreeNode *> generateTrees(int n) { return rec(n, 1, n); }
+ public:
+ vector<TreeNode *> generateTrees(int n) { return rec(n, 1, n); }
};
diff --git a/Problems/0096.cpp b/Problems/0096.cpp
@@ -1,11 +1,12 @@
class Solution {
-public:
- int numTrees(int n) {
- vector<int> dp(n + 1);
- dp[0] = dp[1] = 1;
+ public:
+ int numTrees(int n) {
+ vector<int> dp(n + 1);
+ dp[0] = dp[1] = 1;
- for (int i = 2; i <= n; i++)
- for (int j = 1; j <= i; j++) dp[i] += dp[j - 1] * dp[i - j];
- return dp.back();
- }
+ for (int i = 2; i <= n; i++)
+ for (int j = 1; j <= i; j++)
+ dp[i] += dp[j - 1] * dp[i - j];
+ return dp.back();
+ }
};
diff --git a/Problems/0097.cpp b/Problems/0097.cpp
@@ -1,23 +1,20 @@
class Solution {
- short int dp[101][101];
- bool rec(const string &s1, const string &s2, const string &s3, int i = 0,
- int j = 0, int k = 0) {
- if (k == s3.size()) return true;
- if (dp[i][j] != -1) return dp[i][j];
+ short int dp[101][101];
+ bool rec(const string &s1, const string &s2, const string &s3, int i = 0, int j = 0, int k = 0) {
+ if (k == s3.size()) return true;
+ if (dp[i][j] != -1) return dp[i][j];
- if (i != s1.size() && s1[i] == s3[k] && rec(s1, s2, s3, i + 1, j, k + 1))
- return dp[i][j] = true;
+ if (i != s1.size() && s1[i] == s3[k] && rec(s1, s2, s3, i + 1, j, k + 1)) return dp[i][j] = true;
- if (j != s2.size() && s2[j] == s3[k] && rec(s1, s2, s3, i, j + 1, k + 1))
- return dp[i][j] = true;
+ if (j != s2.size() && s2[j] == s3[k] && rec(s1, s2, s3, i, j + 1, k + 1)) return dp[i][j] = true;
- return dp[i][j] = false;
- }
+ return dp[i][j] = false;
+ }
-public:
- Solution() { memset(dp, 0xFF, sizeof(dp)); }
- bool isInterleave(const string &s1, const string &s2, const string &s3) {
- if (s1.size() + s2.size() != s3.size()) return false;
- return rec(s1, s2, s3);
- }
+ public:
+ Solution() { memset(dp, 0xFF, sizeof(dp)); }
+ bool isInterleave(const string &s1, const string &s2, const string &s3) {
+ if (s1.size() + s2.size() != s3.size()) return false;
+ return rec(s1, s2, s3);
+ }
};
diff --git a/Problems/0098.cpp b/Problems/0098.cpp
@@ -1,20 +1,20 @@
class Solution {
-public:
- bool isValidBST(TreeNode *root) {
- stack<TreeNode *> st;
- long prev = LONG_MIN;
- while (true) {
- while (root) {
- st.push(root);
- root = root->left;
- }
- if (st.empty()) break;
- root = st.top();
- st.pop();
- if (root->val <= prev) return false;
- prev = root->val;
- root = root->right;
+ public:
+ bool isValidBST(TreeNode *root) {
+ stack<TreeNode *> st;
+ long prev = LONG_MIN;
+ while (true) {
+ while (root) {
+ st.push(root);
+ root = root->left;
+ }
+ if (st.empty()) break;
+ root = st.top();
+ st.pop();
+ if (root->val <= prev) return false;
+ prev = root->val;
+ root = root->right;
+ }
+ return true;
}
- return true;
- }
};
diff --git a/Problems/0099.cpp b/Problems/0099.cpp
@@ -1,23 +1,22 @@
class Solution {
-public:
- void recoverTree(TreeNode *root) {
- stack<TreeNode *> st;
- TreeNode *head = root, *prev = new TreeNode(INT_MIN), *l1 = nullptr,
- *l2 = nullptr;
- while (true) {
- while (root) {
- st.push(root);
- root = root->left;
- }
- if (st.empty()) break;
- root = st.top(), st.pop();
- if (root->val < prev->val) {
- if (!l1) l1 = prev;
- l2 = root;
- }
- prev = root;
- root = root->right;
+ public:
+ void recoverTree(TreeNode *root) {
+ stack<TreeNode *> st;
+ TreeNode *head = root, *prev = new TreeNode(INT_MIN), *l1 = nullptr, *l2 = nullptr;
+ while (true) {
+ while (root) {
+ st.push(root);
+ root = root->left;
+ }
+ if (st.empty()) break;
+ root = st.top(), st.pop();
+ if (root->val < prev->val) {
+ if (!l1) l1 = prev;
+ l2 = root;
+ }
+ prev = root;
+ root = root->right;
+ }
+ swap(l1->val, l2->val);
}
- swap(l1->val, l2->val);
- }
};
diff --git a/Problems/0100.cpp b/Problems/0100.cpp
@@ -1,38 +1,37 @@
// Recursive solution
class Solution {
-public:
- bool isSameTree(TreeNode *p, TreeNode *q) {
- if (!p && !q) return true;
- if (!p || !q) return false;
- return p->val == q->val && isSameTree(p->left, q->left) &&
- isSameTree(p->right, q->right);
- }
+ public:
+ bool isSameTree(TreeNode *p, TreeNode *q) {
+ if (!p && !q) return true;
+ if (!p || !q) return false;
+ return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
+ }
};
// Iterative solution
class Solution {
-public:
- bool isSameTree(TreeNode *p, TreeNode *q) {
- if (!p && !q) return true;
- if (!p || !q) return false;
- queue<pair<TreeNode *, TreeNode *>> qu;
- qu.push({p, q});
- while (!qu.empty()) {
- auto [p, q] = qu.front();
- qu.pop();
- if (p->val != q->val) return false;
+ public:
+ bool isSameTree(TreeNode *p, TreeNode *q) {
+ if (!p && !q) return true;
+ if (!p || !q) return false;
+ queue<pair<TreeNode *, TreeNode *>> qu;
+ qu.push({p, q});
+ while (!qu.empty()) {
+ auto [p, q] = qu.front();
+ qu.pop();
+ if (p->val != q->val) return false;
- if (p->left && q->left)
- qu.push({p->left, q->left});
- else if (p->left || q->left)
- return false;
+ if (p->left && q->left)
+ qu.push({p->left, q->left});
+ else if (p->left || q->left)
+ return false;
- if (p->right && q->right)
- qu.push({p->right, q->right});
- else if (p->right || q->right)
- return false;
- }
+ if (p->right && q->right)
+ qu.push({p->right, q->right});
+ else if (p->right || q->right)
+ return false;
+ }
- return true;
- }
+ return true;
+ }
};
diff --git a/Problems/0101.cpp b/Problems/0101.cpp
@@ -1,33 +1,33 @@
class Solution {
- string preorder(TreeNode *root, bool left) {
- if (!root) return "";
+ string preorder(TreeNode *root, bool left) {
+ if (!root) return "";
- string res;
- stack<TreeNode *> st;
- st.push(root);
- while (!st.empty()) {
- TreeNode *root = st.top();
- st.pop();
- if (!root) {
- res += "-";
- continue;
- }
- res += root->val;
- if (left) {
- st.push(root->right);
- st.push(root->left);
- } else {
- st.push(root->left);
- st.push(root->right);
- }
+ string res;
+ stack<TreeNode *> st;
+ st.push(root);
+ while (!st.empty()) {
+ TreeNode *root = st.top();
+ st.pop();
+ if (!root) {
+ res += "-";
+ continue;
+ }
+ res += root->val;
+ if (left) {
+ st.push(root->right);
+ st.push(root->left);
+ } else {
+ st.push(root->left);
+ st.push(root->right);
+ }
+ }
+ return res;
}
- return res;
- }
-public:
- bool isSymmetric(TreeNode *root) {
- if (!root) return false;
+ public:
+ bool isSymmetric(TreeNode *root) {
+ if (!root) return false;
- return preorder(root->left, true) == preorder(root->right, false);
- }
+ return preorder(root->left, true) == preorder(root->right, false);
+ }
};
diff --git a/Problems/0102.cpp b/Problems/0102.cpp
@@ -1,22 +1,22 @@
class Solution {
-public:
- vector<vector<int>> levelOrder(TreeNode *root) {
- if (!root) return {};
+ public:
+ vector<vector<int>> levelOrder(TreeNode *root) {
+ if (!root) return {};
- vector<vector<int>> res;
- queue<TreeNode *> q;
+ vector<vector<int>> res;
+ queue<TreeNode *> q;
- q.push(root);
- for (int lvl = 0; !q.empty(); lvl++) {
- res.push_back(vector<int>());
- for (int t = q.size(); t > 0; t--) {
- TreeNode *root = q.front();
- q.pop();
- res[lvl].push_back(root->val);
- if (root->left) q.push(root->left);
- if (root->right) q.push(root->right);
- }
+ q.push(root);
+ for (int lvl = 0; !q.empty(); lvl++) {
+ res.push_back(vector<int>());
+ for (int t = q.size(); t > 0; t--) {
+ TreeNode *root = q.front();
+ q.pop();
+ res[lvl].push_back(root->val);
+ if (root->left) q.push(root->left);
+ if (root->right) q.push(root->right);
+ }
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0103.cpp b/Problems/0103.cpp
@@ -1,55 +1,55 @@
class Solution {
-public:
- vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
- if (!root) return {};
+ public:
+ vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
+ if (!root) return {};
- vector<vector<int>> res;
- queue<TreeNode *> q;
- bool right = true;
+ vector<vector<int>> res;
+ queue<TreeNode *> q;
+ bool right = true;
- q.push(root);
- for (int lvl = 0; !q.empty(); lvl++) {
- res.push_back(vector<int>());
- for (int t = q.size(); t > 0; t--) {
- TreeNode *root = q.front();
- q.pop();
- res[lvl].push_back(root->val);
+ q.push(root);
+ for (int lvl = 0; !q.empty(); lvl++) {
+ res.push_back(vector<int>());
+ for (int t = q.size(); t > 0; t--) {
+ TreeNode *root = q.front();
+ q.pop();
+ res[lvl].push_back(root->val);
- if (root->left) q.push(root->left);
- if (root->right) q.push(root->right);
- }
- if (!right) reverse(res[lvl].begin(), res[lvl].end());
- right = !right;
+ if (root->left) q.push(root->left);
+ if (root->right) q.push(root->right);
+ }
+ if (!right) reverse(res[lvl].begin(), res[lvl].end());
+ right = !right;
+ }
+ return res;
}
- return res;
- }
- vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
- if (!root) return {};
+ vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
+ if (!root) return {};
- vector<vector<int>> res;
- deque<TreeNode *> d;
- bool right = true;
+ vector<vector<int>> res;
+ deque<TreeNode *> d;
+ bool right = true;
- d.push_front(root);
- for (int lvl = 0; !d.empty(); lvl++, right = !right) {
- res.push_back(vector<int>());
- for (int t = d.size(); t > 0; t--) {
- TreeNode *root;
- if (right) {
- root = d.front();
- d.pop_front();
- if (root->left) d.push_back(root->left);
- if (root->right) d.push_back(root->right);
- } else {
- root = d.back();
- d.pop_back();
- if (root->right) d.push_front(root->right);
- if (root->left) d.push_front(root->left);
+ d.push_front(root);
+ for (int lvl = 0; !d.empty(); lvl++, right = !right) {
+ res.push_back(vector<int>());
+ for (int t = d.size(); t > 0; t--) {
+ TreeNode *root;
+ if (right) {
+ root = d.front();
+ d.pop_front();
+ if (root->left) d.push_back(root->left);
+ if (root->right) d.push_back(root->right);
+ } else {
+ root = d.back();
+ d.pop_back();
+ if (root->right) d.push_front(root->right);
+ if (root->left) d.push_front(root->left);
+ }
+ res[lvl].push_back(root->val);
+ }
}
- res[lvl].push_back(root->val);
- }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0104.cpp b/Problems/0104.cpp
@@ -1,19 +1,19 @@
class Solution {
-public:
- int maxDepth(TreeNode *root) {
- if (!root) return 0;
+ public:
+ int maxDepth(TreeNode *root) {
+ if (!root) return 0;
- int lvl;
- queue<TreeNode *> q;
- q.push(root);
- for (lvl = 0; !q.empty(); lvl++) {
- for (int t = q.size(); t > 0; t--) {
- TreeNode *root = q.front();
- q.pop();
- if (root->left) q.push(root->left);
- if (root->right) q.push(root->right);
- }
+ int lvl;
+ queue<TreeNode *> q;
+ q.push(root);
+ for (lvl = 0; !q.empty(); lvl++) {
+ for (int t = q.size(); t > 0; t--) {
+ TreeNode *root = q.front();
+ q.pop();
+ if (root->left) q.push(root->left);
+ if (root->right) q.push(root->right);
+ }
+ }
+ return lvl;
}
- return lvl;
- }
};
diff --git a/Problems/0105.cpp b/Problems/0105.cpp
@@ -1,31 +1,31 @@
class Solution {
- typedef vector<int>::iterator vii;
- struct Record {
- TreeNode **fill = nullptr;
- vii start, end;
- Record(TreeNode **f, vii s, vii e) : fill(f), start(s), end(e) {}
- };
+ typedef vector<int>::iterator vii;
+ struct Record {
+ TreeNode **fill = nullptr;
+ vii start, end;
+ Record(TreeNode **f, vii s, vii e) : fill(f), start(s), end(e) {}
+ };
-public:
- TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
- stack<Record> st;
- TreeNode head;
- int pre = 0;
+ public:
+ TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
+ stack<Record> st;
+ TreeNode head;
+ int pre = 0;
- st.push({&head.right, inorder.begin(), inorder.end()});
- while (!st.empty()) {
- Record r = st.top();
- st.pop();
- while (r.start < r.end) {
- vii mid = find(r.start, r.end, preorder[pre]);
- if (mid == r.end) break;
- TreeNode *n = *r.fill = new TreeNode(preorder[pre++]);
- st.push({&n->right, next(mid), r.end});
- r.end = mid;
- r.fill = &n->left;
- }
- }
+ st.push({&head.right, inorder.begin(), inorder.end()});
+ while (!st.empty()) {
+ Record r = st.top();
+ st.pop();
+ while (r.start < r.end) {
+ vii mid = find(r.start, r.end, preorder[pre]);
+ if (mid == r.end) break;
+ TreeNode *n = *r.fill = new TreeNode(preorder[pre++]);
+ st.push({&n->right, next(mid), r.end});
+ r.end = mid;
+ r.fill = &n->left;
+ }
+ }
- return head.right;
- }
+ return head.right;
+ }
};
diff --git a/Problems/0106.cpp b/Problems/0106.cpp
@@ -1,32 +1,33 @@
class Solution {
- class Record {
- public:
- int low, high;
- TreeNode **field;
- Record(int l, int h, TreeNode **f) : low(l), high(h), field(f) {}
- };
+ class Record {
+ public:
+ int low, high;
+ TreeNode **field;
+ Record(int l, int h, TreeNode **f) : low(l), high(h), field(f) {}
+ };
-public:
- TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
- unordered_map<int, int> um;
- for (int i = 0; i < inorder.size(); i++) um[inorder[i]] = i;
+ public:
+ TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
+ unordered_map<int, int> um;
+ for (int i = 0; i < inorder.size(); i++)
+ um[inorder[i]] = i;
- int crnt = postorder.size() - 1;
- TreeNode head, *nw;
- stack<Record> st;
+ int crnt = postorder.size() - 1;
+ TreeNode head, *nw;
+ stack<Record> st;
- st.push({0, (int)inorder.size(), &head.right});
- while (!st.empty()) {
- Record r = st.top();
- st.pop();
- while (r.low < r.high) {
- int pos = um[postorder[crnt]];
- nw = *r.field = new TreeNode(postorder[crnt--]);
- st.push({r.low, pos, &nw->left});
- r.low = pos + 1;
- r.field = &nw->right;
- }
+ st.push({0, (int)inorder.size(), &head.right});
+ while (!st.empty()) {
+ Record r = st.top();
+ st.pop();
+ while (r.low < r.high) {
+ int pos = um[postorder[crnt]];
+ nw = *r.field = new TreeNode(postorder[crnt--]);
+ st.push({r.low, pos, &nw->left});
+ r.low = pos + 1;
+ r.field = &nw->right;
+ }
+ }
+ return head.right;
}
- return head.right;
- }
};
diff --git a/Problems/0107.cpp b/Problems/0107.cpp
@@ -1,23 +1,23 @@
class Solution {
-public:
- vector<vector<int>> levelOrderBottom(TreeNode *root) {
- if (!root) return {};
+ public:
+ vector<vector<int>> levelOrderBottom(TreeNode *root) {
+ if (!root) return {};
- vector<vector<int>> res;
- queue<TreeNode *> q;
+ vector<vector<int>> res;
+ queue<TreeNode *> q;
- q.push(root);
- for (int lvl = 0; !q.empty(); lvl++) {
- res.push_back(vector<int>());
- for (int t = q.size(); t > 0; t--) {
- TreeNode *root = q.front();
- q.pop();
- res[lvl].push_back(root->val);
- if (root->left) q.push(root->left);
- if (root->right) q.push(root->right);
- }
+ q.push(root);
+ for (int lvl = 0; !q.empty(); lvl++) {
+ res.push_back(vector<int>());
+ for (int t = q.size(); t > 0; t--) {
+ TreeNode *root = q.front();
+ q.pop();
+ res[lvl].push_back(root->val);
+ if (root->left) q.push(root->left);
+ if (root->right) q.push(root->right);
+ }
+ }
+ reverse(res.begin(), res.end());
+ return res;
}
- reverse(res.begin(), res.end());
- return res;
- }
};
diff --git a/Problems/0108.cpp b/Problems/0108.cpp
@@ -1,27 +1,25 @@
class Solution {
- struct record {
- TreeNode *root;
- int low, high;
- record(TreeNode *root, int low, int high)
- : root(root), low(low), high(high) {}
- };
+ struct record {
+ TreeNode *root;
+ int low, high;
+ record(TreeNode *root, int low, int high) : root(root), low(low), high(high) {}
+ };
-public:
- TreeNode *sortedArrayToBST(vector<int> &nums) {
- stack<record> st;
- TreeNode *head = new TreeNode(INT_MIN), *t;
- st.push({head, 0, (int)nums.size() - 1});
- while (!st.empty()) {
- record r = st.top();
- st.pop();
- while (r.low <= r.high) {
- int mid = r.low + (r.high - r.low) / 2;
- (nums[mid] >= r.root->val ? r.root->right : r.root->left) = t =
- new TreeNode(nums[mid]);
- st.push({r.root = t, mid + 1, r.high});
- r.high = mid - 1;
- }
+ public:
+ TreeNode *sortedArrayToBST(vector<int> &nums) {
+ stack<record> st;
+ TreeNode *head = new TreeNode(INT_MIN), *t;
+ st.push({head, 0, (int)nums.size() - 1});
+ while (!st.empty()) {
+ record r = st.top();
+ st.pop();
+ while (r.low <= r.high) {
+ int mid = r.low + (r.high - r.low) / 2;
+ (nums[mid] >= r.root->val ? r.root->right : r.root->left) = t = new TreeNode(nums[mid]);
+ st.push({r.root = t, mid + 1, r.high});
+ r.high = mid - 1;
+ }
+ }
+ return head->right;
}
- return head->right;
- }
};
diff --git a/Problems/0109.cpp b/Problems/0109.cpp
@@ -1,36 +1,35 @@
class Solution {
- struct record {
- TreeNode *root;
- ListNode *low, *high;
- record(TreeNode *root, ListNode *low = nullptr, ListNode *high = nullptr)
- : root(root), low(low), high(high) {}
- };
- ListNode *get_mid(ListNode *list, ListNode *end) {
- ListNode *slow, *fast;
- slow = fast = list;
- while (fast != end && fast->next != end) {
- fast = fast->next->next;
- slow = slow->next;
+ struct record {
+ TreeNode *root;
+ ListNode *low, *high;
+ record(TreeNode *root, ListNode *low = nullptr, ListNode *high = nullptr)
+ : root(root), low(low), high(high) {}
+ };
+ ListNode *get_mid(ListNode *list, ListNode *end) {
+ ListNode *slow, *fast;
+ slow = fast = list;
+ while (fast != end && fast->next != end) {
+ fast = fast->next->next;
+ slow = slow->next;
+ }
+ return slow;
}
- return slow;
- }
-public:
- TreeNode *sortedListToBST(ListNode *head) {
- stack<record> st;
- TreeNode *tree = new TreeNode(INT_MIN), *t;
- st.push({tree, head, nullptr});
- while (!st.empty()) {
- record r = st.top();
- st.pop();
- while (r.low != r.high) {
- ListNode *mid = get_mid(r.low, r.high);
- (mid->val >= r.root->val ? r.root->right : r.root->left) = t =
- new TreeNode(mid->val);
- st.push({r.root = t, mid->next, r.high});
- r.high = mid;
- }
+ public:
+ TreeNode *sortedListToBST(ListNode *head) {
+ stack<record> st;
+ TreeNode *tree = new TreeNode(INT_MIN), *t;
+ st.push({tree, head, nullptr});
+ while (!st.empty()) {
+ record r = st.top();
+ st.pop();
+ while (r.low != r.high) {
+ ListNode *mid = get_mid(r.low, r.high);
+ (mid->val >= r.root->val ? r.root->right : r.root->left) = t = new TreeNode(mid->val);
+ st.push({r.root = t, mid->next, r.high});
+ r.high = mid;
+ }
+ }
+ return tree->right;
}
- return tree->right;
- }
};
diff --git a/Problems/0110.cpp b/Problems/0110.cpp
@@ -1,23 +1,23 @@
class Solution {
-public:
- bool isBalanced(TreeNode *root) {
- if (!root) return true;
- stack<TreeNode *> st;
- st.push(root);
- while (!st.empty()) {
- TreeNode *root = st.top();
- if (root == nullptr) {
- st.pop(), root = st.top(), st.pop();
- int left = root->left ? root->left->val : 0;
- int right = root->right ? root->right->val : 0;
- if (abs(right - left) > 1) return false;
- root->val = max(left, right) + 1;
- continue;
- }
- st.push(nullptr);
- if (root->left) st.push(root->left);
- if (root->right) st.push(root->right);
+ public:
+ bool isBalanced(TreeNode *root) {
+ if (!root) return true;
+ stack<TreeNode *> st;
+ st.push(root);
+ while (!st.empty()) {
+ TreeNode *root = st.top();
+ if (root == nullptr) {
+ st.pop(), root = st.top(), st.pop();
+ int left = root->left ? root->left->val : 0;
+ int right = root->right ? root->right->val : 0;
+ if (abs(right - left) > 1) return false;
+ root->val = max(left, right) + 1;
+ continue;
+ }
+ st.push(nullptr);
+ if (root->left) st.push(root->left);
+ if (root->right) st.push(root->right);
+ }
+ return true;
}
- return true;
- }
};
diff --git a/Problems/0111.cpp b/Problems/0111.cpp
@@ -1,20 +1,20 @@
class Solution {
-public:
- int minDepth(TreeNode *root) {
- if (!root) return 0;
+ public:
+ int minDepth(TreeNode *root) {
+ if (!root) return 0;
- queue<TreeNode *> q;
+ queue<TreeNode *> q;
- q.push(root);
- for (int lvl = 1; !q.empty(); lvl++) {
- for (int t = q.size(); t > 0; t--) {
- TreeNode *root = q.front();
- q.pop();
- if (!root->left && !root->right) return lvl;
- if (root->left) q.push(root->left);
- if (root->right) q.push(root->right);
- }
+ q.push(root);
+ for (int lvl = 1; !q.empty(); lvl++) {
+ for (int t = q.size(); t > 0; t--) {
+ TreeNode *root = q.front();
+ q.pop();
+ if (!root->left && !root->right) return lvl;
+ if (root->left) q.push(root->left);
+ if (root->right) q.push(root->right);
+ }
+ }
+ return -1;
}
- return -1;
- }
};
diff --git a/Problems/0112.cpp b/Problems/0112.cpp
@@ -1,20 +1,20 @@
class Solution {
-public:
- bool hasPathSum(TreeNode *root, int targetSum) {
- if (!root) return false;
+ public:
+ bool hasPathSum(TreeNode *root, int targetSum) {
+ if (!root) return false;
- stack<pair<TreeNode *, int>> st;
- st.push(make_pair(root, 0));
- while (!st.empty()) {
- TreeNode *root = st.top().first;
- int val = st.top().second + root->val;
- st.pop();
+ stack<pair<TreeNode *, int>> st;
+ st.push(make_pair(root, 0));
+ while (!st.empty()) {
+ TreeNode *root = st.top().first;
+ int val = st.top().second + root->val;
+ st.pop();
- if (val == targetSum && !root->left && !root->right) return true;
+ if (val == targetSum && !root->left && !root->right) return true;
- if (root->left) st.push(make_pair(root->left, val));
- if (root->right) st.push(make_pair(root->right, val));
+ if (root->left) st.push(make_pair(root->left, val));
+ if (root->right) st.push(make_pair(root->right, val));
+ }
+ return false;
}
- return false;
- }
};
diff --git a/Problems/0113.cpp b/Problems/0113.cpp
@@ -1,26 +1,26 @@
class Solution {
-public:
- vector<vector<int>> pathSum(TreeNode *root, int targetSum) {
- if (!root) return {};
- stack<pair<TreeNode *, int>> st;
- vector<vector<int>> res;
- vector<int> path;
- st.push({root, 0});
- while (!st.empty()) {
- auto [root, sum] = st.top();
- if (sum == INT_MIN) {
- st.pop();
- path.pop_back();
- continue;
- }
- sum += root->val;
- st.top().second = INT_MIN;
- path.push_back(root->val);
+ public:
+ vector<vector<int>> pathSum(TreeNode *root, int targetSum) {
+ if (!root) return {};
+ stack<pair<TreeNode *, int>> st;
+ vector<vector<int>> res;
+ vector<int> path;
+ st.push({root, 0});
+ while (!st.empty()) {
+ auto [root, sum] = st.top();
+ if (sum == INT_MIN) {
+ st.pop();
+ path.pop_back();
+ continue;
+ }
+ sum += root->val;
+ st.top().second = INT_MIN;
+ path.push_back(root->val);
- if (!root->left && !root->right && sum == targetSum) res.push_back(path);
- if (root->left) st.push({root->left, sum});
- if (root->right) st.push({root->right, sum});
+ if (!root->left && !root->right && sum == targetSum) res.push_back(path);
+ if (root->left) st.push({root->left, sum});
+ if (root->right) st.push({root->right, sum});
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0114.cpp b/Problems/0114.cpp
@@ -1,21 +1,21 @@
class Solution {
-public:
- void flatten(TreeNode *root) {
- TreeNode *crnt = new TreeNode(-1);
- stack<TreeNode *> st;
- st.push(root);
- while (!st.empty()) {
- TreeNode *root = st.top();
- st.pop();
- crnt->right = root;
- while (root) {
- crnt = root;
- if (root->right) st.push(root->right);
+ public:
+ void flatten(TreeNode *root) {
+ TreeNode *crnt = new TreeNode(-1);
+ stack<TreeNode *> st;
+ st.push(root);
+ while (!st.empty()) {
+ TreeNode *root = st.top();
+ st.pop();
+ crnt->right = root;
+ while (root) {
+ crnt = root;
+ if (root->right) st.push(root->right);
- root->right = root->left;
- root->left = nullptr;
- root = root->right;
- }
+ root->right = root->left;
+ root->left = nullptr;
+ root = root->right;
+ }
+ }
}
- }
};
diff --git a/Problems/0116.cpp b/Problems/0116.cpp
@@ -1,21 +1,21 @@
class Solution {
-public:
- Node *connect(Node *root) {
- if (!root) return {};
+ public:
+ Node *connect(Node *root) {
+ if (!root) return {};
- queue<Node *> q;
- q.push(root);
- for (int lvl = 0; !q.empty(); lvl++) {
- Node *prev = nullptr;
- for (int t = q.size(); t > 0; t--) {
- Node *root = q.front();
- q.pop();
- root->next = prev;
- prev = root;
- if (root->right) q.push(root->right);
- if (root->left) q.push(root->left);
- }
+ queue<Node *> q;
+ q.push(root);
+ for (int lvl = 0; !q.empty(); lvl++) {
+ Node *prev = nullptr;
+ for (int t = q.size(); t > 0; t--) {
+ Node *root = q.front();
+ q.pop();
+ root->next = prev;
+ prev = root;
+ if (root->right) q.push(root->right);
+ if (root->left) q.push(root->left);
+ }
+ }
+ return root;
}
- return root;
- }
};
diff --git a/Problems/0117.cpp b/Problems/0117.cpp
@@ -1,21 +1,21 @@
class Solution {
-public:
- Node *connect(Node *root) {
- if (!root) return {};
+ public:
+ Node *connect(Node *root) {
+ if (!root) return {};
- queue<Node *> q;
- q.push(root);
- for (int lvl = 0; !q.empty(); lvl++) {
- Node *prev = nullptr;
- for (int t = q.size(); t > 0; t--) {
- Node *root = q.front();
- q.pop();
- root->next = prev;
- prev = root;
- if (root->right) q.push(root->right);
- if (root->left) q.push(root->left);
- }
+ queue<Node *> q;
+ q.push(root);
+ for (int lvl = 0; !q.empty(); lvl++) {
+ Node *prev = nullptr;
+ for (int t = q.size(); t > 0; t--) {
+ Node *root = q.front();
+ q.pop();
+ root->next = prev;
+ prev = root;
+ if (root->right) q.push(root->right);
+ if (root->left) q.push(root->left);
+ }
+ }
+ return root;
}
- return root;
- }
};
diff --git a/Problems/0118.cpp b/Problems/0118.cpp
@@ -1,16 +1,16 @@
class Solution {
-public:
- vector<vector<int>> generate(int numRows) {
- vector<vector<int>> res;
+ public:
+ vector<vector<int>> generate(int numRows) {
+ vector<vector<int>> res;
- for (int i = 0; i < numRows; i++) {
- vector<int> row;
- row.push_back(1);
- for (int j = 1; j < i; j++)
- row.push_back(res[i - 1][j - 1] + res[i - 1][j]);
- if (i != 0) row.push_back(1);
- res.push_back(row);
+ for (int i = 0; i < numRows; i++) {
+ vector<int> row;
+ row.push_back(1);
+ for (int j = 1; j < i; j++)
+ row.push_back(res[i - 1][j - 1] + res[i - 1][j]);
+ if (i != 0) row.push_back(1);
+ res.push_back(row);
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0119.cpp b/Problems/0119.cpp
@@ -1,16 +1,16 @@
class Solution {
-public:
- vector<int> getRow(int rowIndex) {
- vector<vector<int>> res;
+ public:
+ vector<int> getRow(int rowIndex) {
+ vector<vector<int>> res;
- for (int i = 0; i <= rowIndex; i++) {
- vector<int> row;
- row.push_back(1);
- for (int j = 1; j < i; j++)
- row.push_back(res[i - 1][j - 1] + res[i - 1][j]);
- if (i != 0) row.push_back(1);
- res.push_back(row);
+ for (int i = 0; i <= rowIndex; i++) {
+ vector<int> row;
+ row.push_back(1);
+ for (int j = 1; j < i; j++)
+ row.push_back(res[i - 1][j - 1] + res[i - 1][j]);
+ if (i != 0) row.push_back(1);
+ res.push_back(row);
+ }
+ return res[rowIndex];
}
- return res[rowIndex];
- }
};
diff --git a/Problems/0120.cpp b/Problems/0120.cpp
@@ -1,16 +1,17 @@
class Solution {
-public:
- int minimumTotal(vector<vector<int>> &triangle) {
- int h = triangle.size();
+ public:
+ int minimumTotal(vector<vector<int>> &triangle) {
+ int h = triangle.size();
- for (int i = 0; i < h - 1; i++) {
- vector<int> vec(i + 2, INT_MAX);
- for (int j = 0; j <= i; j++) {
- vec[j] = min(vec[j], triangle[i][j]);
- vec[j + 1] = min(vec[j + 1], triangle[i][j]);
- }
- for (int j = 0; j <= i + 1; j++) triangle[i + 1][j] += vec[j];
+ for (int i = 0; i < h - 1; i++) {
+ vector<int> vec(i + 2, INT_MAX);
+ for (int j = 0; j <= i; j++) {
+ vec[j] = min(vec[j], triangle[i][j]);
+ vec[j + 1] = min(vec[j + 1], triangle[i][j]);
+ }
+ for (int j = 0; j <= i + 1; j++)
+ triangle[i + 1][j] += vec[j];
+ }
+ return *min_element(triangle.back().begin(), triangle.back().end());
}
- return *min_element(triangle.back().begin(), triangle.back().end());
- }
};
diff --git a/Problems/0121.cpp b/Problems/0121.cpp
@@ -1,12 +1,12 @@
class Solution {
-public:
- int maxProfit(vector<int> &prices) {
- int mini = prices[0];
- int profit = 0;
- for (int i = 1; i < prices.size(); i++) {
- profit = max(prices[i] - mini, profit);
- mini = min(prices[i], mini);
+ public:
+ int maxProfit(vector<int> &prices) {
+ int mini = prices[0];
+ int profit = 0;
+ for (int i = 1; i < prices.size(); i++) {
+ profit = max(prices[i] - mini, profit);
+ mini = min(prices[i], mini);
+ }
+ return profit;
}
- return profit;
- }
};
diff --git a/Problems/0122.cpp b/Problems/0122.cpp
@@ -1,13 +1,14 @@
class Solution {
-public:
- int maxProfit(vector<int> &prices) {
- int profit = 0;
- prices.push_back(INT_MIN);
- for (int i = 0, j = 0; i < prices.size() - 1; i++) {
- while (prices[j] < prices[j + 1]) j++;
- profit += prices[j] - prices[i];
- i = j++;
+ public:
+ int maxProfit(vector<int> &prices) {
+ int profit = 0;
+ prices.push_back(INT_MIN);
+ for (int i = 0, j = 0; i < prices.size() - 1; i++) {
+ while (prices[j] < prices[j + 1])
+ j++;
+ profit += prices[j] - prices[i];
+ i = j++;
+ }
+ return profit;
}
- return profit;
- }
};
diff --git a/Problems/0124.cpp b/Problems/0124.cpp
@@ -1,41 +1,41 @@
class Solution {
-public:
- int maxPathSum(TreeNode *root) {
- if (!root) return 0;
- int res = INT_MIN;
+ public:
+ int maxPathSum(TreeNode *root) {
+ if (!root) return 0;
+ int res = INT_MIN;
- unordered_set<TreeNode *> us;
- stack<TreeNode *> st;
- while (root) {
- st.push(root);
- root = root->left;
- }
- while (!st.empty()) {
- TreeNode *root = st.top();
- st.pop();
-
- if (us.find(root) == us.end()) {
- st.push(root);
- us.insert(root);
- root = root->right;
+ unordered_set<TreeNode *> us;
+ stack<TreeNode *> st;
while (root) {
- st.push(root);
- root = root->left;
+ st.push(root);
+ root = root->left;
+ }
+ while (!st.empty()) {
+ TreeNode *root = st.top();
+ st.pop();
+
+ if (us.find(root) == us.end()) {
+ st.push(root);
+ us.insert(root);
+ root = root->right;
+ while (root) {
+ st.push(root);
+ root = root->left;
+ }
+ } else {
+ int opt = 0, sum = 0;
+ if (root->left) {
+ opt = max(opt, root->left->val), sum += root->left->val;
+ };
+ if (root->right) {
+ opt = max(opt, root->right->val), sum += root->right->val;
+ };
+ res = max(res, root->val + sum);
+ root->val = max(root->val, root->val + opt);
+ res = max(res, root->val);
+ continue;
+ }
}
- } else {
- int opt = 0, sum = 0;
- if (root->left) {
- opt = max(opt, root->left->val), sum += root->left->val;
- };
- if (root->right) {
- opt = max(opt, root->right->val), sum += root->right->val;
- };
- res = max(res, root->val + sum);
- root->val = max(root->val, root->val + opt);
- res = max(res, root->val);
- continue;
- }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0125.cpp b/Problems/0125.cpp
@@ -1,17 +1,17 @@
class Solution {
-public:
- bool isPalindrome(string s) {
- int i = 0, j = s.size() - 1;
- while (i < j) {
- if (!isalnum(s[j]))
- j--;
- else if (!isalnum(s[i]))
- i++;
- else if (tolower(s[i]) != tolower(s[j]))
- return false;
- else
- i++, j--;
+ public:
+ bool isPalindrome(string s) {
+ int i = 0, j = s.size() - 1;
+ while (i < j) {
+ if (!isalnum(s[j]))
+ j--;
+ else if (!isalnum(s[i]))
+ i++;
+ else if (tolower(s[i]) != tolower(s[j]))
+ return false;
+ else
+ i++, j--;
+ }
+ return true;
}
- return true;
- }
};
diff --git a/Problems/0128.cpp b/Problems/0128.cpp
@@ -1,19 +1,20 @@
class Solution {
-public:
- int longestConsecutive(vector<int> &nums) {
- if (!nums.size()) return 0;
+ public:
+ int longestConsecutive(vector<int> &nums) {
+ if (!nums.size()) return 0;
- unordered_set<int> us(nums.begin(), nums.end());
- int res = 0;
+ unordered_set<int> us(nums.begin(), nums.end());
+ int res = 0;
- for (int num : us) {
- if (!us.count(num - 1)) {
- int crnt = num;
- while (us.count(crnt + 1)) crnt += 1;
- res = max(longestStreak, crnt - num);
- }
- }
+ for (int num : us) {
+ if (!us.count(num - 1)) {
+ int crnt = num;
+ while (us.count(crnt + 1))
+ crnt += 1;
+ res = max(longestStreak, crnt - num);
+ }
+ }
- return res + 1;
- }
+ return res + 1;
+ }
};
diff --git a/Problems/0129.cpp b/Problems/0129.cpp
@@ -1,26 +1,26 @@
class Solution {
-public:
- int sumNumbers(TreeNode *root) {
- if (!root) return 0;
+ public:
+ int sumNumbers(TreeNode *root) {
+ if (!root) return 0;
- int sum = 0, res = 0;
- stack<pair<TreeNode *, int>> st;
- while (true) {
- while (root) {
- sum *= 10;
- sum += root->val;
- if (root->right)
- st.push({root->right, sum});
- else if (!root->left)
- res += sum;
- root = root->left;
- }
- if (st.empty()) break;
- root = st.top().first;
- sum = st.top().second;
- st.pop();
- }
+ int sum = 0, res = 0;
+ stack<pair<TreeNode *, int>> st;
+ while (true) {
+ while (root) {
+ sum *= 10;
+ sum += root->val;
+ if (root->right)
+ st.push({root->right, sum});
+ else if (!root->left)
+ res += sum;
+ root = root->left;
+ }
+ if (st.empty()) break;
+ root = st.top().first;
+ sum = st.top().second;
+ st.pop();
+ }
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0130.cpp b/Problems/0130.cpp
@@ -1,53 +1,48 @@
class Solution {
- typedef vector<vector<char>> Matrix;
- typedef queue<pair<int, int>> Queue;
- const vector<pair<int, int>> offsets = {
- { 0, 1},
- { 0, -1},
- { 1, 0},
- {-1, 0}
- };
-
- int n, m;
-
- int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }
-
- void dfs(Matrix &board, int x, int y) {
- Queue q;
-
- q.push({x, y}), board[x][y] = '#';
- while (!q.empty()) {
- auto [a, b] = q.front();
- q.pop();
- for (auto [oa, ob] : offsets) {
- int x = a + oa, y = b + ob;
- if (!valid(x, y) || board[x][y] == 'X' || board[x][y] != 'O') continue;
- board[x][y] = '#';
- q.push({x, y});
- }
+ typedef vector<vector<char>> Matrix;
+ typedef queue<pair<int, int>> Queue;
+ const vector<pair<int, int>> offsets = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
+
+ int n, m;
+
+ int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }
+
+ void dfs(Matrix &board, int x, int y) {
+ Queue q;
+
+ q.push({x, y}), board[x][y] = '#';
+ while (!q.empty()) {
+ auto [a, b] = q.front();
+ q.pop();
+ for (auto [oa, ob] : offsets) {
+ int x = a + oa, y = b + ob;
+ if (!valid(x, y) || board[x][y] == 'X' || board[x][y] != 'O') continue;
+ board[x][y] = '#';
+ q.push({x, y});
+ }
+ }
}
- }
-public:
- void solve(Matrix &board) {
- n = board.size(), m = board[0].size();
+ public:
+ void solve(Matrix &board) {
+ n = board.size(), m = board[0].size();
- unordered_set<int> convert;
- Queue q;
- int group = 0;
+ unordered_set<int> convert;
+ Queue q;
+ int group = 0;
- for (int i = 0; i < n; i++) {
- if (board[i][0] == 'O') dfs(board, i, 0);
- if (board[i][m - 1] == 'O') dfs(board, i, m - 1);
- }
+ for (int i = 0; i < n; i++) {
+ if (board[i][0] == 'O') dfs(board, i, 0);
+ if (board[i][m - 1] == 'O') dfs(board, i, m - 1);
+ }
- for (int j = 0; j < m; j++) {
- if (board[0][j] == 'O') dfs(board, 0, j);
- if (board[n - 1][j] == 'O') dfs(board, n - 1, j);
- }
+ for (int j = 0; j < m; j++) {
+ if (board[0][j] == 'O') dfs(board, 0, j);
+ if (board[n - 1][j] == 'O') dfs(board, n - 1, j);
+ }
- for (int i = 0; i < n; i++)
- for (int j = 0; j < m; j++)
- if (board[i][j] != 'X') board[i][j] = board[i][j] == 'O' ? 'X' : 'O';
- }
+ for (int i = 0; i < n; i++)
+ for (int j = 0; j < m; j++)
+ if (board[i][j] != 'X') board[i][j] = board[i][j] == 'O' ? 'X' : 'O';
+ }
};
diff --git a/Problems/0131.cpp b/Problems/0131.cpp
@@ -1,60 +1,60 @@
// Backtracking
class Solution {
- vector<string> st;
- vector<vector<string>> res;
-
- bool valid(const string &s) {
- int i = 0, j = s.size() - 1;
- while (i < j)
- if (s[i++] != s[j--]) return false;
- return true;
- }
-
- void dfs(const string &s, int pos) {
- if (pos == s.size()) res.push_back(st);
-
- string crnt = "";
- for (int i = pos; i < s.size(); i++) {
- crnt += s[i];
- if (valid(crnt)) {
- st.push_back(crnt);
- dfs(s, i + 1);
- st.pop_back();
- }
+ vector<string> st;
+ vector<vector<string>> res;
+
+ bool valid(const string &s) {
+ int i = 0, j = s.size() - 1;
+ while (i < j)
+ if (s[i++] != s[j--]) return false;
+ return true;
}
- }
-public:
- vector<vector<string>> partition(string s) {
- dfs(s, 0);
- return res;
- }
+ void dfs(const string &s, int pos) {
+ if (pos == s.size()) res.push_back(st);
+
+ string crnt = "";
+ for (int i = pos; i < s.size(); i++) {
+ crnt += s[i];
+ if (valid(crnt)) {
+ st.push_back(crnt);
+ dfs(s, i + 1);
+ st.pop_back();
+ }
+ }
+ }
+
+ public:
+ vector<vector<string>> partition(string s) {
+ dfs(s, 0);
+ return res;
+ }
};
// Backtracking with DP
class Solution {
- vector<string> st;
- vector<vector<string>> res;
-
- void dfs(const string &s, int pos, vector<vector<bool>> &dp) {
- if (pos == s.size()) res.push_back(st);
-
- string crnt = "";
- for (int i = pos; i < s.size(); i++) {
- crnt += s[i];
- if (s[pos] == s[i] && (i - pos < 2 || dp[pos + 1][i - 1])) {
- dp[pos][i] = true;
- st.push_back(crnt);
- dfs(s, i + 1, dp);
- st.pop_back();
- }
+ vector<string> st;
+ vector<vector<string>> res;
+
+ void dfs(const string &s, int pos, vector<vector<bool>> &dp) {
+ if (pos == s.size()) res.push_back(st);
+
+ string crnt = "";
+ for (int i = pos; i < s.size(); i++) {
+ crnt += s[i];
+ if (s[pos] == s[i] && (i - pos < 2 || dp[pos + 1][i - 1])) {
+ dp[pos][i] = true;
+ st.push_back(crnt);
+ dfs(s, i + 1, dp);
+ st.pop_back();
+ }
+ }
+ }
+
+ public:
+ vector<vector<string>> partition(string s) {
+ vector<vector<bool>> dp(s.size(), vector<bool>(s.size(), false));
+ dfs(s, 0, dp);
+ return res;
}
- }
-
-public:
- vector<vector<string>> partition(string s) {
- vector<vector<bool>> dp(s.size(), vector<bool>(s.size(), false));
- dfs(s, 0, dp);
- return res;
- }
};
diff --git a/Problems/0133.cpp b/Problems/0133.cpp
@@ -1,29 +1,27 @@
class Solution {
-public:
- Node *cloneGraph(Node *node) {
- if (!node) return nullptr;
+ public:
+ Node *cloneGraph(Node *node) {
+ if (!node) return nullptr;
- Node *head = new Node(node->val);
- unordered_map<Node *, Node *> um({
- {node, head}
- });
+ Node *head = new Node(node->val);
+ unordered_map<Node *, Node *> um({{node, head}});
- stack<Node *> st;
- st.push(node);
- while (!st.empty()) {
- Node *node = st.top();
- st.pop();
- for (Node *c : node->neighbors) {
- if (um.find(c) != um.end()) {
- um[node]->neighbors.push_back(um[c]);
- continue;
+ stack<Node *> st;
+ st.push(node);
+ while (!st.empty()) {
+ Node *node = st.top();
+ st.pop();
+ for (Node *c : node->neighbors) {
+ if (um.find(c) != um.end()) {
+ um[node]->neighbors.push_back(um[c]);
+ continue;
+ }
+ Node *n = new Node(c->val);
+ um[node]->neighbors.push_back(n);
+ um.insert(make_pair(c, n));
+ st.push(c);
+ }
}
- Node *n = new Node(c->val);
- um[node]->neighbors.push_back(n);
- um.insert(make_pair(c, n));
- st.push(c);
- }
+ return head;
}
- return head;
- }
};
diff --git a/Problems/0134.cpp b/Problems/0134.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
- int start = 0, total = 0, tank = 0;
- for (int i = 0; i < gas.size(); i++) {
- tank = tank + gas[i] - cost[i];
- if (tank < 0) {
- start = i + 1;
- total += tank;
- tank = 0;
- }
+ public:
+ int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
+ int start = 0, total = 0, tank = 0;
+ for (int i = 0; i < gas.size(); i++) {
+ tank = tank + gas[i] - cost[i];
+ if (tank < 0) {
+ start = i + 1;
+ total += tank;
+ tank = 0;
+ }
+ }
+ return (total + tank >= 0) ? start : -1;
}
- return (total + tank >= 0) ? start : -1;
- }
};
diff --git a/Problems/0135.cpp b/Problems/0135.cpp
@@ -1,47 +1,46 @@
// original solution - accepted
class Solution {
-public:
- int candy(vector<int> &ratings) {
- // place holder rating for easy neighbor calculation
- ratings.insert(ratings.begin(), -1), ratings.push_back(-1);
- int n = ratings.size();
-
- // sort by rating remembering the original index
- vector<pair<int, int>> vec;
- vec.reserve(n);
- for (int i = 1; i < n - 1; i++) vec.push_back({ratings[i], i});
- sort(vec.begin(), vec.end());
-
- vector<int> res(n, 1); // 'Each child must have at least one candy'
- res.front() = res.back() = 0; // except placeholders
- for (auto &[rating, index] : vec) {
- if (rating < ratings[index + 1])
- res[index + 1] = max(res[index + 1], res[index] + 1);
-
- if (rating < ratings[index - 1])
- res[index - 1] = max(res[index - 1], res[index] + 1);
+ public:
+ int candy(vector<int> &ratings) {
+ // place holder rating for easy neighbor calculation
+ ratings.insert(ratings.begin(), -1), ratings.push_back(-1);
+ int n = ratings.size();
+
+ // sort by rating remembering the original index
+ vector<pair<int, int>> vec;
+ vec.reserve(n);
+ for (int i = 1; i < n - 1; i++)
+ vec.push_back({ratings[i], i});
+ sort(vec.begin(), vec.end());
+
+ vector<int> res(n, 1); // 'Each child must have at least one candy'
+ res.front() = res.back() = 0; // except placeholders
+ for (auto &[rating, index] : vec) {
+ if (rating < ratings[index + 1]) res[index + 1] = max(res[index + 1], res[index] + 1);
+
+ if (rating < ratings[index - 1]) res[index - 1] = max(res[index - 1], res[index] + 1);
+ }
+
+ return accumulate(res.begin(), res.end(), 0);
}
-
- return accumulate(res.begin(), res.end(), 0);
- }
};
// improved solution - same logic no nonsense
class Solution {
-public:
- int candy(vector<int> &ratings) {
- int n = ratings.size();
- if (n <= 1) return n;
-
- vector<int> res(n, 1);
- for (int i = 0; i < n - 1; i++) {
- if (ratings[i] < ratings[i + 1]) res[i + 1] = res[i] + 1;
- }
+ public:
+ int candy(vector<int> &ratings) {
+ int n = ratings.size();
+ if (n <= 1) return n;
- for (int i = n - 1; i > 0; i--) {
- if (ratings[i] < ratings[i - 1]) res[i - 1] = max(res[i - 1], res[i] + 1);
- }
+ vector<int> res(n, 1);
+ for (int i = 0; i < n - 1; i++) {
+ if (ratings[i] < ratings[i + 1]) res[i + 1] = res[i] + 1;
+ }
- return accumulate(res.begin(), res.end(), 0);
- }
+ for (int i = n - 1; i > 0; i--) {
+ if (ratings[i] < ratings[i - 1]) res[i - 1] = max(res[i - 1], res[i] + 1);
+ }
+
+ return accumulate(res.begin(), res.end(), 0);
+ }
};
diff --git a/Problems/0136.cpp b/Problems/0136.cpp
@@ -1,8 +1,9 @@
class Solution {
-public:
- int singleNumber(vector<int> &nums) {
- int res = 0;
- for (const int n : nums) res ^= n;
- return res;
- }
+ public:
+ int singleNumber(vector<int> &nums) {
+ int res = 0;
+ for (const int n : nums)
+ res ^= n;
+ return res;
+ }
};
diff --git a/Problems/0137.cpp b/Problems/0137.cpp
@@ -1,11 +1,11 @@
class Solution {
-public:
- int singleNumber(const vector<int> &nums) {
- int mask1 = 0, mask2 = 0;
- for (int n : nums) {
- mask1 = (mask1 ^ n) & ~mask2;
- mask2 = (mask2 ^ n) & ~mask1;
+ public:
+ int singleNumber(const vector<int> &nums) {
+ int mask1 = 0, mask2 = 0;
+ for (int n : nums) {
+ mask1 = (mask1 ^ n) & ~mask2;
+ mask2 = (mask2 ^ n) & ~mask1;
+ }
+ return mask1;
}
- return mask1;
- }
};
diff --git a/Problems/0138.cpp b/Problems/0138.cpp
@@ -1,20 +1,20 @@
class Solution {
-public:
- Node *copyRandomList(Node *head) {
- if (!head) return nullptr;
+ public:
+ Node *copyRandomList(Node *head) {
+ if (!head) return nullptr;
- unordered_map<Node *, Node *> um;
- Node *h, *t;
- t = h = new Node(-1);
- for (Node *p = head; p; p = p->next) {
- t = t->next = new Node(p->val);
- um.insert(make_pair(p, t));
- }
+ unordered_map<Node *, Node *> um;
+ Node *h, *t;
+ t = h = new Node(-1);
+ for (Node *p = head; p; p = p->next) {
+ t = t->next = new Node(p->val);
+ um.insert(make_pair(p, t));
+ }
- t = h->next;
- for (Node *p = head; p; p = p->next, t = t->next) {
- if (p->random != nullptr) t->random = um[p->random];
+ t = h->next;
+ for (Node *p = head; p; p = p->next, t = t->next) {
+ if (p->random != nullptr) t->random = um[p->random];
+ }
+ return h->next;
}
- return h->next;
- }
};
diff --git a/Problems/0139.cpp b/Problems/0139.cpp
@@ -1 +1 @@
-Formating: Problems/0139.cpp
+Formating : Problems / 0139.cpp
diff --git a/Problems/0141.cpp b/Problems/0141.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- bool hasCycle(ListNode *head) {
- if (!head) return false;
+ public:
+ bool hasCycle(ListNode *head) {
+ if (!head) return false;
- ListNode *slow, *fast;
- fast = slow = head;
- while (fast->next && fast->next->next) {
- fast = fast->next->next;
- slow = slow->next;
- if (fast == slow) return true;
+ ListNode *slow, *fast;
+ fast = slow = head;
+ while (fast->next && fast->next->next) {
+ fast = fast->next->next;
+ slow = slow->next;
+ if (fast == slow) return true;
+ }
+ return false;
}
- return false;
- }
};
diff --git a/Problems/0142.cpp b/Problems/0142.cpp
@@ -1,22 +1,22 @@
class Solution {
-public:
- ListNode *detectCycle(ListNode *head) {
- if (!head) return nullptr;
+ public:
+ ListNode *detectCycle(ListNode *head) {
+ if (!head) return nullptr;
- ListNode *slow, *fast;
- fast = slow = head;
- while (fast->next && fast->next->next) {
- fast = fast->next->next;
- slow = slow->next;
- if (fast == slow) {
- fast = head;
- while (fast != slow) {
- fast = fast->next;
- slow = slow->next;
+ ListNode *slow, *fast;
+ fast = slow = head;
+ while (fast->next && fast->next->next) {
+ fast = fast->next->next;
+ slow = slow->next;
+ if (fast == slow) {
+ fast = head;
+ while (fast != slow) {
+ fast = fast->next;
+ slow = slow->next;
+ }
+ return slow;
+ }
}
- return slow;
- }
+ return nullptr;
}
- return nullptr;
- }
};
diff --git a/Problems/0143.cpp b/Problems/0143.cpp
@@ -1,42 +1,42 @@
class Solution {
- ListNode *reverseList(ListNode *head) {
- ListNode *p, *q, *r;
+ ListNode *reverseList(ListNode *head) {
+ ListNode *p, *q, *r;
- p = head, q = nullptr;
- while (p) {
- r = q;
- q = p;
- p = p->next;
- q->next = r;
+ p = head, q = nullptr;
+ while (p) {
+ r = q;
+ q = p;
+ p = p->next;
+ q->next = r;
+ }
+
+ return q;
}
- return q;
- }
+ ListNode *bmiddleNode(ListNode *head) {
+ ListNode *fast, *slow;
+ fast = slow = head;
+ while (fast->next && fast->next->next) {
+ fast = fast->next->next;
+ slow = slow->next;
+ }
- ListNode *bmiddleNode(ListNode *head) {
- ListNode *fast, *slow;
- fast = slow = head;
- while (fast->next && fast->next->next) {
- fast = fast->next->next;
- slow = slow->next;
+ return slow;
}
- return slow;
- }
-
-public:
- void reorderList(ListNode *head) {
- ListNode *bmid = bmiddleNode(head);
- ListNode *rev = reverseList(bmid->next);
- bmid->next = nullptr;
+ public:
+ void reorderList(ListNode *head) {
+ ListNode *bmid = bmiddleNode(head);
+ ListNode *rev = reverseList(bmid->next);
+ bmid->next = nullptr;
- ListNode top, *tmp = &top, *a, *b, *an;
- for (a = head, b = rev; b; b = b->next, a = an) {
- an = a->next;
- tmp = tmp->next = a;
- tmp = tmp->next = b;
+ ListNode top, *tmp = &top, *a, *b, *an;
+ for (a = head, b = rev; b; b = b->next, a = an) {
+ an = a->next;
+ tmp = tmp->next = a;
+ tmp = tmp->next = b;
+ }
+ if (a) tmp = tmp->next = a;
+ tmp->next = nullptr;
}
- if (a) tmp = tmp->next = a;
- tmp->next = nullptr;
- }
};
diff --git a/Problems/0144.cpp b/Problems/0144.cpp
@@ -1,20 +1,20 @@
class Solution {
-public:
- vector<int> preorderTraversal(TreeNode *root) {
- if (!root) return {};
+ public:
+ vector<int> preorderTraversal(TreeNode *root) {
+ if (!root) return {};
- vector<int> res;
- stack<TreeNode *> st;
- st.push(root);
- while (!st.empty()) {
- TreeNode *root = st.top();
- st.pop();
- while (root) {
- res.push_back(root->val);
- if (root->right) st.push(root->right);
- root = root->left;
- }
+ vector<int> res;
+ stack<TreeNode *> st;
+ st.push(root);
+ while (!st.empty()) {
+ TreeNode *root = st.top();
+ st.pop();
+ while (root) {
+ res.push_back(root->val);
+ if (root->right) st.push(root->right);
+ root = root->left;
+ }
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0145.cpp b/Problems/0145.cpp
@@ -1,33 +1,33 @@
class Solution {
-public:
- vector<int> postorderTraversal(TreeNode *root) {
- if (!root) return {};
+ public:
+ vector<int> postorderTraversal(TreeNode *root) {
+ if (!root) return {};
- vector<int> res;
- unordered_set<TreeNode *> s;
- stack<TreeNode *> st;
+ vector<int> res;
+ unordered_set<TreeNode *> s;
+ stack<TreeNode *> st;
- while (root) {
- st.push(root);
- root = root->left;
- }
-
- while (!st.empty()) {
- TreeNode *root = st.top();
- st.pop();
- if (!s.count(root)) {
- s.insert(root);
- st.push(root);
- root = root->right;
while (root) {
- st.push(root);
- root = root->left;
+ st.push(root);
+ root = root->left;
}
- } else {
- res.push_back(root->val);
- }
- }
- return res;
- }
+ while (!st.empty()) {
+ TreeNode *root = st.top();
+ st.pop();
+ if (!s.count(root)) {
+ s.insert(root);
+ st.push(root);
+ root = root->right;
+ while (root) {
+ st.push(root);
+ root = root->left;
+ }
+ } else {
+ res.push_back(root->val);
+ }
+ }
+
+ return res;
+ }
};
diff --git a/Problems/0146.cpp b/Problems/0146.cpp
@@ -1,37 +1,37 @@
class LRUCache {
- unordered_map<int, pair<int, int>> um;
- queue<pair<int, int>> q;
- int capacity;
+ unordered_map<int, pair<int, int>> um;
+ queue<pair<int, int>> q;
+ int capacity;
-public:
- LRUCache(int capacity) : capacity(capacity) {}
+ public:
+ LRUCache(int capacity) : capacity(capacity) {}
- int get(int key) {
- auto it = um.find(key);
- if (it == um.end()) return -1;
- q.push({key, ++it->second.first});
- return it->second.second;
- }
-
- void put(int key, int value) {
- auto it = um.find(key);
- if (it != um.end()) {
- q.push({key, ++it->second.first});
- it->second.second = value;
- return;
+ int get(int key) {
+ auto it = um.find(key);
+ if (it == um.end()) return -1;
+ q.push({key, ++it->second.first});
+ return it->second.second;
}
- if (um.size() == capacity) {
- while (true) {
- auto [key, time] = q.front();
- q.pop();
- if (um[key].first == time) {
- um.erase(key);
- break;
+ void put(int key, int value) {
+ auto it = um.find(key);
+ if (it != um.end()) {
+ q.push({key, ++it->second.first});
+ it->second.second = value;
+ return;
+ }
+
+ if (um.size() == capacity) {
+ while (true) {
+ auto [key, time] = q.front();
+ q.pop();
+ if (um[key].first == time) {
+ um.erase(key);
+ break;
+ }
+ }
}
- }
+ q.push({key, 0});
+ um[key] = {0, value};
}
- q.push({key, 0});
- um[key] = {0, value};
- }
};
diff --git a/Problems/0148.cpp b/Problems/0148.cpp
@@ -1,38 +1,37 @@
class Solution {
-public:
- ListNode *sortList(ListNode *head) {
- if (!head || !head->next) return head;
- ListNode *mid = getMid(head), *left = sortList(head),
- *right = sortList(mid);
- return merge(left, right);
- }
+ public:
+ ListNode *sortList(ListNode *head) {
+ if (!head || !head->next) return head;
+ ListNode *mid = getMid(head), *left = sortList(head), *right = sortList(mid);
+ return merge(left, right);
+ }
- ListNode *merge(ListNode *list1, ListNode *list2) {
- ListNode head, *t = &head;
+ ListNode *merge(ListNode *list1, ListNode *list2) {
+ ListNode head, *t = &head;
- while (list1 && list2) {
- if (list1->val < list2->val) {
- t = t->next = list1;
- list1 = list1->next;
- } else {
- t = t->next = list2;
- list2 = list2->next;
- }
- }
+ while (list1 && list2) {
+ if (list1->val < list2->val) {
+ t = t->next = list1;
+ list1 = list1->next;
+ } else {
+ t = t->next = list2;
+ list2 = list2->next;
+ }
+ }
- t->next = list1 ? list1 : list2;
- return head.next;
- }
+ t->next = list1 ? list1 : list2;
+ return head.next;
+ }
- ListNode *getMid(ListNode *head) {
- ListNode *fast, *slow;
- fast = slow = head;
- while (fast->next && fast->next->next) {
- fast = fast->next->next;
- slow = slow->next;
+ ListNode *getMid(ListNode *head) {
+ ListNode *fast, *slow;
+ fast = slow = head;
+ while (fast->next && fast->next->next) {
+ fast = fast->next->next;
+ slow = slow->next;
+ }
+ fast = slow->next;
+ slow->next = nullptr;
+ return fast;
}
- fast = slow->next;
- slow->next = nullptr;
- return fast;
- }
};
diff --git a/Problems/0149.cpp b/Problems/0149.cpp
@@ -1,18 +1,19 @@
class Solution {
-public:
- int maxPoints(vector<vector<int>> &points) {
- int n = points.size();
- if (n == 1) return 1;
+ public:
+ int maxPoints(vector<vector<int>> &points) {
+ int n = points.size();
+ if (n == 1) return 1;
- int res = 2;
- for (int i = 0; i < n; i++) {
- unordered_map<double, int> um;
- for (int j = 0; j < n; j++) {
- if (j == i) continue;
- um[atan2(points[j][1] - points[i][1], points[j][0] - points[i][0])]++;
- }
- for (auto [_, count] : um) res = max(res, count + 1);
+ int res = 2;
+ for (int i = 0; i < n; i++) {
+ unordered_map<double, int> um;
+ for (int j = 0; j < n; j++) {
+ if (j == i) continue;
+ um[atan2(points[j][1] - points[i][1], points[j][0] - points[i][0])]++;
+ }
+ for (auto [_, count] : um)
+ res = max(res, count + 1);
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0150.cpp b/Problems/0150.cpp
@@ -1,28 +1,26 @@
class Solution {
- bool is_op(const string &s) {
- return s == "+" || s == "-" || s == "*" || s == "/";
- }
+ bool is_op(const string &s) { return s == "+" || s == "-" || s == "*" || s == "/"; }
-public:
- int evalRPN(vector<string> &tokens) {
- if (tokens.size() == 0) return 0;
+ public:
+ int evalRPN(vector<string> &tokens) {
+ if (tokens.size() == 0) return 0;
- stack<long long> st;
- for (string &s : tokens) {
- if (is_op(s)) {
- long long y = st.top();
- st.pop();
- long long x = st.top();
- st.pop();
- switch (s[0]) {
- case '+': st.push(x + y); break;
- case '-': st.push(x - y); break;
- case '*': st.push(x * y); break;
- case '/': st.push(x / y); break;
+ stack<long long> st;
+ for (string &s : tokens) {
+ if (is_op(s)) {
+ long long y = st.top();
+ st.pop();
+ long long x = st.top();
+ st.pop();
+ switch (s[0]) {
+ case '+': st.push(x + y); break;
+ case '-': st.push(x - y); break;
+ case '*': st.push(x * y); break;
+ case '/': st.push(x / y); break;
+ }
+ } else
+ st.push(stoi(s));
}
- } else
- st.push(stoi(s));
+ return st.top();
}
- return st.top();
- }
};
diff --git a/Problems/0151.cpp b/Problems/0151.cpp
@@ -1,18 +1,18 @@
class Solution {
-public:
- string reverseWords(string s) {
- string res = "";
- string buff = "";
- for (int i = 0; i < s.size(); i++) {
- if (s[i] != ' ') {
- buff += s[i];
- } else if (buff != "") {
- res = buff + " " + res;
- buff = "";
- }
+ public:
+ string reverseWords(string s) {
+ string res = "";
+ string buff = "";
+ for (int i = 0; i < s.size(); i++) {
+ if (s[i] != ' ') {
+ buff += s[i];
+ } else if (buff != "") {
+ res = buff + " " + res;
+ buff = "";
+ }
+ }
+ if (buff != "") res = buff + " " + res;
+ if (res != "") res.pop_back();
+ return res;
}
- if (buff != "") res = buff + " " + res;
- if (res != "") res.pop_back();
- return res;
- }
};
diff --git a/Problems/0152.cpp b/Problems/0152.cpp
@@ -1,3 +1 @@
-Formating: Problems/0152.cpp
-Formating: Problems/0300.cpp
-Formating: Problems/1567.cpp
+Formating : Problems / 0152.cpp Formating : Problems / 0300.cpp Formating : Problems / 1567.cpp
diff --git a/Problems/0153.cpp b/Problems/0153.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- int findMin(vector<int> &nums) {
- int low = 0, high = nums.size() - 1;
- while (low < high) {
- if (nums[low] < nums[high]) return nums[low];
- int mid = low + (high - low) / 2;
- if (nums[mid] >= nums[low])
- low = mid + 1;
- else
- high = mid;
+ public:
+ int findMin(vector<int> &nums) {
+ int low = 0, high = nums.size() - 1;
+ while (low < high) {
+ if (nums[low] < nums[high]) return nums[low];
+ int mid = low + (high - low) / 2;
+ if (nums[mid] >= nums[low])
+ low = mid + 1;
+ else
+ high = mid;
+ }
+ return nums[low];
}
- return nums[low];
- }
};
diff --git a/Problems/0155.cpp b/Problems/0155.cpp
@@ -1,12 +1,10 @@
class MinStack {
- stack<pair<int, int>> st;
+ stack<pair<int, int>> st;
-public:
- MinStack() {}
- void push(int val) {
- st.push({val, !st.size() ? val : min(val, st.top().second)});
- }
- void pop() { st.pop(); }
- int top() { return st.top().first; }
- int getMin() { return st.top().second; }
+ public:
+ MinStack() {}
+ void push(int val) { st.push({val, !st.size() ? val : min(val, st.top().second)}); }
+ void pop() { st.pop(); }
+ int top() { return st.top().first; }
+ int getMin() { return st.top().second; }
};
diff --git a/Problems/0160.cpp b/Problems/0160.cpp
@@ -1,20 +1,22 @@
class Solution {
-public:
- ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
- if (!headA || !headB) return nullptr;
+ public:
+ ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
+ if (!headA || !headB) return nullptr;
- ListNode *res = nullptr;
+ ListNode *res = nullptr;
- for (ListNode *p = headA; p; p = p->next) p->val = -p->val;
+ for (ListNode *p = headA; p; p = p->next)
+ p->val = -p->val;
- for (ListNode *p = headB; p; p = p->next)
- if (p->val < 0) {
- res = p;
- break;
- }
+ for (ListNode *p = headB; p; p = p->next)
+ if (p->val < 0) {
+ res = p;
+ break;
+ }
- for (ListNode *p = headA; p; p = p->next) p->val = -p->val;
+ for (ListNode *p = headA; p; p = p->next)
+ p->val = -p->val;
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0162.cpp b/Problems/0162.cpp
@@ -1,16 +1,16 @@
class Solution {
-public:
- int findPeakElement(vector<int>& nums) {
+ public:
+ int findPeakElement(vector<int> &nums) {
int n = nums.size();
- if(n==1) return 0;
+ if (n == 1) return 0;
- for(int i=0; i<n-1; ) {
- if(nums[i]>nums[i+1]) return i;
- i+=2;
- if(i>=n) break;
- if(nums[i-1]>nums[i]) return i-1;
+ for (int i = 0; i < n - 1;) {
+ if (nums[i] > nums[i + 1]) return i;
+ i += 2;
+ if (i >= n) break;
+ if (nums[i - 1] > nums[i]) return i - 1;
}
- if(nums[n-1]>nums[n-2]) return n-1;
+ if (nums[n - 1] > nums[n - 2]) return n - 1;
return -1;
}
diff --git a/Problems/0164.cpp b/Problems/0164.cpp
@@ -1,4 +1,3 @@
-Formating: Problems/0164.cpp
-Formating: Problems/0164.cpp
-Formating: Problems/0912.cpp
-Formating: Problems/2343.cpp
+Formating
+ : Problems /
+ 0164.cpp Formating : Problems / 0164.cpp Formating : Problems / 0912.cpp Formating : Problems / 2343.cpp
diff --git a/Problems/0165.cpp b/Problems/0165.cpp
@@ -1,25 +1,29 @@
class Solution {
-public:
- int compareVersion(string version1, string version2) {
- stringstream s1(version1), s2(version2);
- vector<int> v1, v2;
+ public:
+ int compareVersion(string version1, string version2) {
+ stringstream s1(version1), s2(version2);
+ vector<int> v1, v2;
- string crnt;
- while (getline(s1, crnt, '.')) v1.push_back(stoi(crnt));
- while (getline(s2, crnt, '.')) v2.push_back(stoi(crnt));
+ string crnt;
+ while (getline(s1, crnt, '.'))
+ v1.push_back(stoi(crnt));
+ while (getline(s2, crnt, '.'))
+ v2.push_back(stoi(crnt));
- while (v1.size() < v2.size()) v1.push_back(0);
- while (v1.size() > v2.size()) v2.push_back(0);
+ while (v1.size() < v2.size())
+ v1.push_back(0);
+ while (v1.size() > v2.size())
+ v2.push_back(0);
- int i = 0, j = 0;
- while (i < v1.size() && j < v2.size()) {
- if (v1[i] > v2[j]) return 1;
- if (v1[i] < v2[j])
- return -1;
- else
- i++, j++;
- }
+ int i = 0, j = 0;
+ while (i < v1.size() && j < v2.size()) {
+ if (v1[i] > v2[j]) return 1;
+ if (v1[i] < v2[j])
+ return -1;
+ else
+ i++, j++;
+ }
- return 0;
- }
+ return 0;
+ }
};
diff --git a/Problems/0167.cpp b/Problems/0167.cpp
@@ -1,16 +1,16 @@
class Solution {
-public:
- vector<int> twoSum(vector<int> &numbers, int target) {
- int i = 0, j = numbers.size() - 1;
- while (i < j) {
- int sum = numbers[i] + numbers[j];
- if (sum == target)
- return {i + 1, j + 1};
- else if (sum < target)
- i++;
- else
- j--;
+ public:
+ vector<int> twoSum(vector<int> &numbers, int target) {
+ int i = 0, j = numbers.size() - 1;
+ while (i < j) {
+ int sum = numbers[i] + numbers[j];
+ if (sum == target)
+ return {i + 1, j + 1};
+ else if (sum < target)
+ i++;
+ else
+ j--;
+ }
+ return {};
}
- return {};
- }
};
diff --git a/Problems/0168.cpp b/Problems/0168.cpp
@@ -1,12 +1,12 @@
class Solution {
-public:
- string convertToTitle(int columnNumber) {
- string res = "";
- do {
- columnNumber -= 1;
- res += 'A' + columnNumber % 26;
- } while ((columnNumber /= 26));
- reverse(res.begin(), res.end());
- return res;
- }
+ public:
+ string convertToTitle(int columnNumber) {
+ string res = "";
+ do {
+ columnNumber -= 1;
+ res += 'A' + columnNumber % 26;
+ } while ((columnNumber /= 26));
+ reverse(res.begin(), res.end());
+ return res;
+ }
};
diff --git a/Problems/0169.cpp b/Problems/0169.cpp
@@ -1,10 +1,11 @@
class Solution {
-public:
- int majorityElement(const vector<int> &nums) {
- unordered_map<int, unsigned> um;
- for (int n : nums) um[n]++;
- for (auto [k, v] : um)
- if (v > (nums.size() / 2)) return k;
- return -1;
- }
+ public:
+ int majorityElement(const vector<int> &nums) {
+ unordered_map<int, unsigned> um;
+ for (int n : nums)
+ um[n]++;
+ for (auto [k, v] : um)
+ if (v > (nums.size() / 2)) return k;
+ return -1;
+ }
};
diff --git a/Problems/0171.cpp b/Problems/0171.cpp
@@ -1,11 +1,11 @@
class Solution {
-public:
- int titleToNumber(string columnTitle) {
- int res = 0;
- for (char c : columnTitle) {
- res *= 26;
- res += c - 'A' + 1;
+ public:
+ int titleToNumber(string columnTitle) {
+ int res = 0;
+ for (char c : columnTitle) {
+ res *= 26;
+ res += c - 'A' + 1;
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0173.cpp b/Problems/0173.cpp
@@ -1,52 +1,52 @@
// Naive approach using vector to precompute in-order traversal
class BSTIterator {
- vector<int> vec;
- int current = 0;
-
-public:
- BSTIterator(TreeNode *root) {
- stack<TreeNode *> st;
- while (true) {
- while (root) {
- st.push(root);
- root = root->left;
- }
- if (st.empty()) break;
- root = st.top();
- st.pop();
- vec.push_back(root->val);
- root = root->right;
+ vector<int> vec;
+ int current = 0;
+
+ public:
+ BSTIterator(TreeNode *root) {
+ stack<TreeNode *> st;
+ while (true) {
+ while (root) {
+ st.push(root);
+ root = root->left;
+ }
+ if (st.empty()) break;
+ root = st.top();
+ st.pop();
+ vec.push_back(root->val);
+ root = root->right;
+ }
}
- }
- int next() { return vec[current++]; }
+ int next() { return vec[current++]; }
- bool hasNext() { return current < vec.size(); }
+ bool hasNext() { return current < vec.size(); }
};
// Compute in-order on the fly
class BSTIterator {
- stack<TreeNode *> st;
+ stack<TreeNode *> st;
- void fill_stack(TreeNode *root) {
- while (root) {
- st.push(root);
- root = root->left;
+ void fill_stack(TreeNode *root) {
+ while (root) {
+ st.push(root);
+ root = root->left;
+ }
}
- }
-public:
- BSTIterator(TreeNode *root) { fill_stack(root); }
+ public:
+ BSTIterator(TreeNode *root) { fill_stack(root); }
- int next() {
- int val = st.top()->val;
- TreeNode *root = st.top()->right;
- st.pop();
- fill_stack(root);
- return val;
- }
+ int next() {
+ int val = st.top()->val;
+ TreeNode *root = st.top()->right;
+ st.pop();
+ fill_stack(root);
+ return val;
+ }
- bool hasNext() { return !st.empty(); }
+ bool hasNext() { return !st.empty(); }
};
diff --git a/Problems/0179.cpp b/Problems/0179.cpp
@@ -1,18 +1,18 @@
class Solution {
-public:
- string largestNumber(const vector<int> &nums) {
- const static auto cmp = [](const string &x, const string &y) {
- return x + y > y + x;
- };
+ public:
+ string largestNumber(const vector<int> &nums) {
+ const static auto cmp = [](const string &x, const string &y) { return x + y > y + x; };
- vector<string> v(nums.size());
- for (int i = 0; i < v.size(); i++) v[i] = to_string(nums[i]);
+ vector<string> v(nums.size());
+ for (int i = 0; i < v.size(); i++)
+ v[i] = to_string(nums[i]);
- sort(v.begin(), v.end(), cmp);
- if (v[0] == "0") return "0";
+ sort(v.begin(), v.end(), cmp);
+ if (v[0] == "0") return "0";
- string res = "";
- for (int i = 0; i < v.size(); i++) res += v[i];
- return res;
- }
+ string res = "";
+ for (int i = 0; i < v.size(); i++)
+ res += v[i];
+ return res;
+ }
};
diff --git a/Problems/0187.cpp b/Problems/0187.cpp
@@ -1,58 +1,60 @@
// Left to right
class Solution {
-public:
- vector<string> findRepeatedDnaSequences(string s) {
- if (s.size() <= 10) return {};
-
- unordered_map<string, int> um;
- vector<string> res;
- string sec = "";
-
- for (int i = 0; i < 10; i++) sec += s[i];
- um[sec]++;
- for (int i = 10; i < s.size(); i++) {
- sec = sec.substr(1) + s[i];
- if (um[sec]++ == 1) res.push_back(sec);
+ public:
+ vector<string> findRepeatedDnaSequences(string s) {
+ if (s.size() <= 10) return {};
+
+ unordered_map<string, int> um;
+ vector<string> res;
+ string sec = "";
+
+ for (int i = 0; i < 10; i++)
+ sec += s[i];
+ um[sec]++;
+ for (int i = 10; i < s.size(); i++) {
+ sec = sec.substr(1) + s[i];
+ if (um[sec]++ == 1) res.push_back(sec);
+ }
+
+ return res;
}
-
- return res;
- }
};
// Right to left
class Solution {
-public:
- vector<string> findRepeatedDnaSequences(string s) {
- if (s.size() <= 10) return {};
-
- unordered_map<string, int> um;
- vector<string> res;
- string sec = "";
-
- for (int i = s.size() - 1; i >= s.size() - 10; i--) sec = s[i] + sec;
- um[sec]++;
- for (int i = s.size() - 10 - 1; i >= 0; i--) {
- sec.pop_back();
- sec = s[i] + sec;
- if (um[sec]++ == 1) res.push_back(sec);
+ public:
+ vector<string> findRepeatedDnaSequences(string s) {
+ if (s.size() <= 10) return {};
+
+ unordered_map<string, int> um;
+ vector<string> res;
+ string sec = "";
+
+ for (int i = s.size() - 1; i >= s.size() - 10; i--)
+ sec = s[i] + sec;
+ um[sec]++;
+ for (int i = s.size() - 10 - 1; i >= 0; i--) {
+ sec.pop_back();
+ sec = s[i] + sec;
+ if (um[sec]++ == 1) res.push_back(sec);
+ }
+
+ return res;
}
-
- return res;
- }
};
// Bit hacking
class Solution {
-public:
- vector<string> findRepeatedDnaSequences(string s) {
- unordered_map<unsigned, int> um;
- vector<string> res;
-
- for (unsigned i = 0, sec = 0; i < s.size(); i++) {
- sec = sec << 3 & 0x3FFFFFFF | s[i] & 7;
- if (um[sec]++ == 1) res.push_back(s.substr(i - 9, 10));
- }
+ public:
+ vector<string> findRepeatedDnaSequences(string s) {
+ unordered_map<unsigned, int> um;
+ vector<string> res;
- return res;
- }
+ for (unsigned i = 0, sec = 0; i < s.size(); i++) {
+ sec = sec << 3 & 0x3FFFFFFF | s[i] & 7;
+ if (um[sec]++ == 1) res.push_back(s.substr(i - 9, 10));
+ }
+
+ return res;
+ }
};
diff --git a/Problems/0189.cpp b/Problems/0189.cpp
@@ -1,22 +1,25 @@
// O(n) memory solution
class Solution {
-public:
- void rotate(vector<int> &nums, int k) {
- k %= nums.size();
- vector<int> t(k);
- for (int i = 0; i < k; i++) t[i] = nums[nums.size() - k + i];
- for (int i = nums.size() - k - 1; i >= 0; i--) nums[i + k] = nums[i];
- for (int i = 0; i < k; i++) nums[i] = t[i];
- }
+ public:
+ void rotate(vector<int> &nums, int k) {
+ k %= nums.size();
+ vector<int> t(k);
+ for (int i = 0; i < k; i++)
+ t[i] = nums[nums.size() - k + i];
+ for (int i = nums.size() - k - 1; i >= 0; i--)
+ nums[i + k] = nums[i];
+ for (int i = 0; i < k; i++)
+ nums[i] = t[i];
+ }
};
// O(1) memory solution
class Solution {
-public:
- void rotate(vector<int> &nums, int k) {
- k %= nums.size();
- reverse(nums.begin(), nums.end());
- reverse(nums.begin(), nums.begin() + k);
- reverse(nums.begin() + k, nums.end());
- }
+ public:
+ void rotate(vector<int> &nums, int k) {
+ k %= nums.size();
+ reverse(nums.begin(), nums.end());
+ reverse(nums.begin(), nums.begin() + k);
+ reverse(nums.begin() + k, nums.end());
+ }
};
diff --git a/Problems/0190.cpp b/Problems/0190.cpp
@@ -1,12 +1,12 @@
class Solution {
-public:
- uint32_t reverseBits(uint32_t n) {
- int count = 32, res = 0;
- while (count--) {
- res <<= 1;
- res += n & 1;
- n >>= 1;
+ public:
+ uint32_t reverseBits(uint32_t n) {
+ int count = 32, res = 0;
+ while (count--) {
+ res <<= 1;
+ res += n & 1;
+ n >>= 1;
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0191.cpp b/Problems/0191.cpp
@@ -1,8 +1,9 @@
class Solution {
-public:
- int hammingWeight(uint32_t n) {
- int res = 0;
- while (n) res += n & 1, n >>= 1;
- return res;
- }
+ public:
+ int hammingWeight(uint32_t n) {
+ int res = 0;
+ while (n)
+ res += n & 1, n >>= 1;
+ return res;
+ }
};
diff --git a/Problems/0198.cpp b/Problems/0198.cpp
@@ -1,13 +1,13 @@
class Solution {
-public:
- int rob(vector<int> &nums) {
- if (nums.size() == 0) return 0;
- int prev1 = 0, prev2 = 0;
- for (int num : nums) {
- int tmp = prev1;
- prev1 = max(prev2 + num, prev1);
- prev2 = tmp;
+ public:
+ int rob(vector<int> &nums) {
+ if (nums.size() == 0) return 0;
+ int prev1 = 0, prev2 = 0;
+ for (int num : nums) {
+ int tmp = prev1;
+ prev1 = max(prev2 + num, prev1);
+ prev2 = tmp;
+ }
+ return prev1;
}
- return prev1;
- }
};
diff --git a/Problems/0199.cpp b/Problems/0199.cpp
@@ -1,20 +1,20 @@
class Solution {
-public:
- vector<int> rightSideView(TreeNode *root) {
- if (!root) return {};
+ public:
+ vector<int> rightSideView(TreeNode *root) {
+ if (!root) return {};
- vector<int> res;
- queue<TreeNode *> q;
- q.push(root);
- for (int lvl = 0; !q.empty(); lvl++) {
- res.push_back(q.front()->val);
- for (int k = q.size(); k > 0; k--) {
- TreeNode *root = q.front();
- q.pop();
- if (root->right) q.push(root->right);
- if (root->left) q.push(root->left);
- }
+ vector<int> res;
+ queue<TreeNode *> q;
+ q.push(root);
+ for (int lvl = 0; !q.empty(); lvl++) {
+ res.push_back(q.front()->val);
+ for (int k = q.size(); k > 0; k--) {
+ TreeNode *root = q.front();
+ q.pop();
+ if (root->right) q.push(root->right);
+ if (root->left) q.push(root->left);
+ }
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0200.cpp b/Problems/0200.cpp
@@ -1,27 +1,27 @@
class Solution {
-public:
- int numIslands(vector<vector<char>> &grid) {
- queue<pair<int, int>> q;
- int cnt = 0;
- int m = grid.size(), n = grid[0].size();
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < n; j++) {
- if (grid[i][j] == '0') continue;
- q.push(make_pair(i, j));
- cnt++;
- while (!q.empty()) {
- int i = q.front().first;
- int j = q.front().second;
- q.pop();
- if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') continue;
- grid[i][j] = '0';
- q.push(make_pair(i + 1, j));
- q.push(make_pair(i - 1, j));
- q.push(make_pair(i, j + 1));
- q.push(make_pair(i, j - 1));
+ public:
+ int numIslands(vector<vector<char>> &grid) {
+ queue<pair<int, int>> q;
+ int cnt = 0;
+ int m = grid.size(), n = grid[0].size();
+ for (int i = 0; i < m; i++) {
+ for (int j = 0; j < n; j++) {
+ if (grid[i][j] == '0') continue;
+ q.push(make_pair(i, j));
+ cnt++;
+ while (!q.empty()) {
+ int i = q.front().first;
+ int j = q.front().second;
+ q.pop();
+ if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') continue;
+ grid[i][j] = '0';
+ q.push(make_pair(i + 1, j));
+ q.push(make_pair(i - 1, j));
+ q.push(make_pair(i, j + 1));
+ q.push(make_pair(i, j - 1));
+ }
+ }
}
- }
+ return cnt;
}
- return cnt;
- }
};
diff --git a/Problems/0201.cpp b/Problems/0201.cpp
@@ -1,9 +1,8 @@
class Solution {
-public:
+ public:
int rangeBitwiseAnd(int left, int right) {
int cnt = 0;
- while(left != right)
- {
+ while (left != right) {
cnt++;
left >>= 1;
right >>= 1;
diff --git a/Problems/0202.cpp b/Problems/0202.cpp
@@ -1,14 +1,16 @@
class Solution {
-public:
- bool isHappy(int n) {
- unordered_set<int> seen;
- int tmp;
+ public:
+ bool isHappy(int n) {
+ unordered_set<int> seen;
+ int tmp;
- while (n != 1 && !seen.count(n)) {
- seen.insert(n);
- tmp = n, n = 0;
- do { n += (tmp % 10) * (tmp % 10); } while ((tmp /= 10) > 0);
+ while (n != 1 && !seen.count(n)) {
+ seen.insert(n);
+ tmp = n, n = 0;
+ do {
+ n += (tmp % 10) * (tmp % 10);
+ } while ((tmp /= 10) > 0);
+ }
+ return !seen.count(n);
}
- return !seen.count(n);
- }
};
diff --git a/Problems/0203.cpp b/Problems/0203.cpp
@@ -1,16 +1,16 @@
class Solution {
-public:
- ListNode *removeElements(ListNode *head, int val) {
- if (!head) return nullptr;
+ public:
+ ListNode *removeElements(ListNode *head, int val) {
+ if (!head) return nullptr;
- for (ListNode *p = head; p && p->next;)
- if (p->next->val == val)
- p->next = p->next->next;
- else
- p = p->next;
+ for (ListNode *p = head; p && p->next;)
+ if (p->next->val == val)
+ p->next = p->next->next;
+ else
+ p = p->next;
- if (head->val == val) head = head->next;
+ if (head->val == val) head = head->next;
- return head;
- }
+ return head;
+ }
};
diff --git a/Problems/0204.cpp b/Problems/0204.cpp
@@ -1,13 +1,14 @@
class Solution {
-public:
- int countPrimes(int n) {
- vector<bool> sieve(n);
- int res = 0;
- for (long i = 2; i < n; i++) {
- if (sieve[i]) continue;
- for (long j = i * i; j < n; j += i) sieve[j] = true;
- res++;
+ public:
+ int countPrimes(int n) {
+ vector<bool> sieve(n);
+ int res = 0;
+ for (long i = 2; i < n; i++) {
+ if (sieve[i]) continue;
+ for (long j = i * i; j < n; j += i)
+ sieve[j] = true;
+ res++;
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0205.cpp b/Problems/0205.cpp
@@ -1,18 +1,18 @@
class Solution {
-public:
- bool isIsomorphic(string s, string t) {
- unordered_map<char, char> um;
- unordered_set<char> us;
+ public:
+ bool isIsomorphic(string s, string t) {
+ unordered_map<char, char> um;
+ unordered_set<char> us;
- for (int i = 0; i < s.size(); i++) {
- if (!um.count(s[i])) {
- if (us.count(t[i])) return false;
- um[s[i]] = t[i];
- us.insert(t[i]);
- } else if (um[s[i]] != t[i])
- return false;
- }
+ for (int i = 0; i < s.size(); i++) {
+ if (!um.count(s[i])) {
+ if (us.count(t[i])) return false;
+ um[s[i]] = t[i];
+ us.insert(t[i]);
+ } else if (um[s[i]] != t[i])
+ return false;
+ }
- return true;
- }
+ return true;
+ }
};
diff --git a/Problems/0206.cpp b/Problems/0206.cpp
@@ -1,16 +1,16 @@
class Solution {
-public:
- ListNode *reverseList(ListNode *head) {
- ListNode *p, *q, *r;
+ public:
+ ListNode *reverseList(ListNode *head) {
+ ListNode *p, *q, *r;
- p = head, q = nullptr;
- while (p) {
- r = q;
- q = p;
- p = p->next;
- q->next = r;
- }
+ p = head, q = nullptr;
+ while (p) {
+ r = q;
+ q = p;
+ p = p->next;
+ q->next = r;
+ }
- return q;
- }
+ return q;
+ }
};
diff --git a/Problems/0207.cpp b/Problems/0207.cpp
@@ -1,28 +1,28 @@
class Solution {
- static int adj[2048][2048];
+ static int adj[2048][2048];
-public:
- bool canFinish(int n, const vector<vector<int>> &prerequisites) {
- int count[2048] = {0}, size[2048] = {0};
+ public:
+ bool canFinish(int n, const vector<vector<int>> &prerequisites) {
+ int count[2048] = {0}, size[2048] = {0};
- for (auto &p : prerequisites) {
- adj[p[0]][size[p[0]]++] = p[1];
- count[p[1]]++;
- }
+ for (auto &p : prerequisites) {
+ adj[p[0]][size[p[0]]++] = p[1];
+ count[p[1]]++;
+ }
- queue<int> q;
- for (int i = 0; i < n; i++)
- if (!count[i]) q.push(i);
+ queue<int> q;
+ for (int i = 0; i < n; i++)
+ if (!count[i]) q.push(i);
- while (!q.empty()) {
- int root = q.front();
- q.pop(), n--;
- for (int i = 0; i < size[root]; i++)
- if (!--count[adj[root][i]]) q.push(adj[root][i]);
- }
+ while (!q.empty()) {
+ int root = q.front();
+ q.pop(), n--;
+ for (int i = 0; i < size[root]; i++)
+ if (!--count[adj[root][i]]) q.push(adj[root][i]);
+ }
- return n == 0;
- }
+ return n == 0;
+ }
};
int Solution::adj[2048][2048];
diff --git a/Problems/0208.cpp b/Problems/0208.cpp
@@ -1,39 +1,40 @@
class Trie {
- struct Record {
- bool end;
- array<Record *, 26> records = {nullptr};
+ struct Record {
+ bool end;
+ array<Record *, 26> records = {nullptr};
- Record *insert(int x) {
- if (records[x]) return records[x];
- return records[x] = new Record();
- }
+ Record *insert(int x) {
+ if (records[x]) return records[x];
+ return records[x] = new Record();
+ }
- Record *check(int x) { return records[x]; }
- };
+ Record *check(int x) { return records[x]; }
+ };
- Record *record = new Record;
- Record *last(string word) {
- Record *crnt = record;
- for (char c : word)
- if (!crnt)
- return nullptr;
- else
- crnt = crnt->check(c - 'a');
- return crnt;
- }
+ Record *record = new Record;
+ Record *last(string word) {
+ Record *crnt = record;
+ for (char c : word)
+ if (!crnt)
+ return nullptr;
+ else
+ crnt = crnt->check(c - 'a');
+ return crnt;
+ }
-public:
- void insert(string word) {
- Record *crnt = record;
- for (char c : word) crnt = crnt->insert(c - 'a');
- crnt->end = true;
- }
+ public:
+ void insert(string word) {
+ Record *crnt = record;
+ for (char c : word)
+ crnt = crnt->insert(c - 'a');
+ crnt->end = true;
+ }
- bool search(string word) {
- Record *crnt = last(word);
- if (!crnt) return false;
- return crnt->end;
- }
+ bool search(string word) {
+ Record *crnt = last(word);
+ if (!crnt) return false;
+ return crnt->end;
+ }
- bool startsWith(string prefix) { return last(prefix); }
+ bool startsWith(string prefix) { return last(prefix); }
};
diff --git a/Problems/0209.cpp b/Problems/0209.cpp
@@ -1,17 +1,17 @@
class Solution {
-public:
- int minSubArrayLen(int target, const vector<int> &nums) {
- int i = 0, j = 0, sum = 0, res = nums.size() + 1;
- while (true) {
- if (sum >= target) {
- res = min(res, j - i);
- sum -= nums[i++];
- } else {
- if (j == nums.size()) break;
- sum += nums[j++];
- }
+ public:
+ int minSubArrayLen(int target, const vector<int> &nums) {
+ int i = 0, j = 0, sum = 0, res = nums.size() + 1;
+ while (true) {
+ if (sum >= target) {
+ res = min(res, j - i);
+ sum -= nums[i++];
+ } else {
+ if (j == nums.size()) break;
+ sum += nums[j++];
+ }
+ }
+ if (res == nums.size() + 1) return 0;
+ return res;
}
- if (res == nums.size() + 1) return 0;
- return res;
- }
};
diff --git a/Problems/0210.cpp b/Problems/0210.cpp
@@ -1,28 +1,28 @@
class Solution {
-public:
- vector<int> findOrder(int n, vector<vector<int>> &prerequisites) {
- vector<vector<int>> adj(n);
- vector<int> count(n, 0);
- vector<int> res;
- int num = 0;
+ public:
+ vector<int> findOrder(int n, vector<vector<int>> &prerequisites) {
+ vector<vector<int>> adj(n);
+ vector<int> count(n, 0);
+ vector<int> res;
+ int num = 0;
- for (auto &p : prerequisites) {
- adj[p[1]].push_back(p[0]);
- count[p[0]]++;
- }
+ for (auto &p : prerequisites) {
+ adj[p[1]].push_back(p[0]);
+ count[p[0]]++;
+ }
- queue<int> q;
- for (int i = 0; i < n; i++)
- if (!count[i]) q.push(i);
+ queue<int> q;
+ for (int i = 0; i < n; i++)
+ if (!count[i]) q.push(i);
- while (!q.empty()) {
- int root = q.front();
- q.pop();
- res.push_back(root);
- n--;
- for (int c : adj[root])
- if (!--count[c]) q.push(c);
+ while (!q.empty()) {
+ int root = q.front();
+ q.pop();
+ res.push_back(root);
+ n--;
+ for (int c : adj[root])
+ if (!--count[c]) q.push(c);
+ }
+ return n == 0 ? res : vector<int>();
}
- return n == 0 ? res : vector<int>();
- }
};
diff --git a/Problems/0211.cpp b/Problems/0211.cpp
@@ -1,32 +1,31 @@
class WordDictionary {
- vector<WordDictionary *> children;
- bool isEndOfWord = false;
- ;
+ vector<WordDictionary *> children;
+ bool isEndOfWord = false;
+ ;
-public:
- WordDictionary() : children(vector<WordDictionary *>(26, nullptr)) {}
+ public:
+ WordDictionary() : children(vector<WordDictionary *>(26, nullptr)) {}
- void addWord(string word) {
- WordDictionary *crnt = this;
- for (char c : word) {
- if (crnt->children[c - 'a'] == nullptr)
- crnt->children[c - 'a'] = new WordDictionary();
- crnt = crnt->children[c - 'a'];
+ void addWord(string word) {
+ WordDictionary *crnt = this;
+ for (char c : word) {
+ if (crnt->children[c - 'a'] == nullptr) crnt->children[c - 'a'] = new WordDictionary();
+ crnt = crnt->children[c - 'a'];
+ }
+ crnt->isEndOfWord = true;
}
- crnt->isEndOfWord = true;
- }
- bool search(string word) {
- WordDictionary *crnt = this;
- for (int i = 0; i < word.length(); ++i) {
- if (word[i] == '.') {
- for (auto c : crnt->children)
- if (c && c->search(word.substr(i + 1))) return true;
- return false;
- }
- if (crnt->children[word[i] - 'a'] == nullptr) return false;
- crnt = crnt->children[word[i] - 'a'];
+ bool search(string word) {
+ WordDictionary *crnt = this;
+ for (int i = 0; i < word.length(); ++i) {
+ if (word[i] == '.') {
+ for (auto c : crnt->children)
+ if (c && c->search(word.substr(i + 1))) return true;
+ return false;
+ }
+ if (crnt->children[word[i] - 'a'] == nullptr) return false;
+ crnt = crnt->children[word[i] - 'a'];
+ }
+ return crnt && crnt->isEndOfWord;
}
- return crnt && crnt->isEndOfWord;
- }
};
diff --git a/Problems/0213.cpp b/Problems/0213.cpp
@@ -1,20 +1,19 @@
class Solution {
-public:
- // see 198. House Robber
- int rob_single(vector<int> &nums, int start, int end) {
- if (end - start <= 0) return 0;
- int prev1 = 0, prev2 = 0;
- for (int i = start; i < end; i++) {
- int tmp = prev1;
- prev1 = max(prev2 + nums[i], prev1);
- prev2 = tmp;
+ public:
+ // see 198. House Robber
+ int rob_single(vector<int> &nums, int start, int end) {
+ if (end - start <= 0) return 0;
+ int prev1 = 0, prev2 = 0;
+ for (int i = start; i < end; i++) {
+ int tmp = prev1;
+ prev1 = max(prev2 + nums[i], prev1);
+ prev2 = tmp;
+ }
+ return prev1;
}
- return prev1;
- }
- int rob(vector<int> &nums) {
- if (nums.size() == 0) return 0;
- return max(nums[0] + rob_single(nums, 2, nums.size() - 1),
- rob_single(nums, 1, nums.size()));
- }
+ int rob(vector<int> &nums) {
+ if (nums.size() == 0) return 0;
+ return max(nums[0] + rob_single(nums, 2, nums.size() - 1), rob_single(nums, 1, nums.size()));
+ }
};
diff --git a/Problems/0215.cpp b/Problems/0215.cpp
@@ -1,13 +1,13 @@
class Solution {
-public:
- int findKthLargest(vector<int> &nums, int k) {
- priority_queue<int, vector<int>, greater<int>> pq;
+ public:
+ int findKthLargest(vector<int> &nums, int k) {
+ priority_queue<int, vector<int>, greater<int>> pq;
- for (int num : nums) {
- pq.push(num);
- if (pq.size() > k) pq.pop();
- }
+ for (int num : nums) {
+ pq.push(num);
+ if (pq.size() > k) pq.pop();
+ }
- return pq.top();
- }
+ return pq.top();
+ }
};
diff --git a/Problems/0217.cpp b/Problems/0217.cpp
@@ -1,20 +1,20 @@
class Solution {
-public:
- bool containsDuplicate(vector<int> &nums) {
- unordered_set<int> us;
- for (int n : nums)
- if (us.count(n))
- return true;
- else
- us.insert(n);
- return false;
- }
+ public:
+ bool containsDuplicate(vector<int> &nums) {
+ unordered_set<int> us;
+ for (int n : nums)
+ if (us.count(n))
+ return true;
+ else
+ us.insert(n);
+ return false;
+ }
};
// Fun oneliner
class Solution {
-public:
- bool containsDuplicate(vector<int> &nums) {
- return nums.size() > unordered_set<int>(nums.begin(), nums.end()).size();
- }
+ public:
+ bool containsDuplicate(vector<int> &nums) {
+ return nums.size() > unordered_set<int>(nums.begin(), nums.end()).size();
+ }
};
diff --git a/Problems/0219.cpp b/Problems/0219.cpp
@@ -1,19 +1,19 @@
class Solution {
-public:
- bool containsNearbyDuplicate(vector<int> &nums, int k) {
- unordered_set<int> us;
- int n = nums.size(), i;
- for (i = 0; i <= k && i < n; i++) {
- if (us.count(nums[i])) return true;
- us.insert(nums[i]);
- }
+ public:
+ bool containsNearbyDuplicate(vector<int> &nums, int k) {
+ unordered_set<int> us;
+ int n = nums.size(), i;
+ for (i = 0; i <= k && i < n; i++) {
+ if (us.count(nums[i])) return true;
+ us.insert(nums[i]);
+ }
- for (; i < n; i++) {
- us.erase(nums[i - k - 1]);
- if (us.count(nums[i])) return true;
- us.insert(nums[i]);
- }
+ for (; i < n; i++) {
+ us.erase(nums[i - k - 1]);
+ if (us.count(nums[i])) return true;
+ us.insert(nums[i]);
+ }
- return false;
- }
+ return false;
+ }
};
diff --git a/Problems/0221.cpp b/Problems/0221.cpp
@@ -1,18 +1,18 @@
class Solution {
-public:
- int maximalSquare(vector<vector<char>> &matrix) {
- int n = matrix.size(), m = matrix[0].size(), res = 0;
- vector<vector<int>> dp(n, vector<int>(m, 0));
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < m; j++) {
- if (!i || !j || matrix[i][j] == '0') {
- dp[i][j] = matrix[i][j] - '0';
- } else {
- dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1;
+ public:
+ int maximalSquare(vector<vector<char>> &matrix) {
+ int n = matrix.size(), m = matrix[0].size(), res = 0;
+ vector<vector<int>> dp(n, vector<int>(m, 0));
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < m; j++) {
+ if (!i || !j || matrix[i][j] == '0') {
+ dp[i][j] = matrix[i][j] - '0';
+ } else {
+ dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1;
+ }
+ res = max(res, dp[i][j]);
+ }
}
- res = max(res, dp[i][j]);
- }
+ return res * res;
}
- return res * res;
- }
};
diff --git a/Problems/0222.cpp b/Problems/0222.cpp
@@ -1,25 +1,27 @@
class Solution {
-public:
- int countNodes(TreeNode *root) {
- if (!root) return 0;
+ public:
+ int countNodes(TreeNode *root) {
+ if (!root) return 0;
- int height = 0;
- queue<TreeNode *> q;
- q.push(root);
- while (!q.empty()) {
- TreeNode *root = q.front();
- q.pop();
- int rh = 0, lh = 0;
- for (TreeNode *t = root; t; t = t->left) lh++;
- for (TreeNode *t = root; t; t = t->right) rh++;
- if (lh == rh)
- height += exp2(rh) - 1;
- else {
- height++;
- if (root->left) q.push(root->left);
- if (root->right) q.push(root->right);
- }
+ int height = 0;
+ queue<TreeNode *> q;
+ q.push(root);
+ while (!q.empty()) {
+ TreeNode *root = q.front();
+ q.pop();
+ int rh = 0, lh = 0;
+ for (TreeNode *t = root; t; t = t->left)
+ lh++;
+ for (TreeNode *t = root; t; t = t->right)
+ rh++;
+ if (lh == rh)
+ height += exp2(rh) - 1;
+ else {
+ height++;
+ if (root->left) q.push(root->left);
+ if (root->right) q.push(root->right);
+ }
+ }
+ return height;
}
- return height;
- }
};
diff --git a/Problems/0223.cpp b/Problems/0223.cpp
@@ -1,20 +1,17 @@
class Solution {
- int calc_area(int x1, int y1, int x2, int y2) {
- return abs(x1 - x2) * abs(y1 - y2);
- }
+ int calc_area(int x1, int y1, int x2, int y2) { return abs(x1 - x2) * abs(y1 - y2); }
-public:
- int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2,
- int by2) {
- int area = calc_area(ax1, ay1, ax2, ay2) + calc_area(bx1, by1, bx2, by2);
- int x1, x2, y1, y2;
- x1 = max(ax1, bx1);
- x2 = min(ax2, bx2);
- y1 = max(ay1, by1);
- y2 = min(ay2, by2);
- if (x2 - x1 > 0 && y2 - y1 > 0)
- return area - calc_area(x1, y1, x2, y2);
- else
- return area;
- }
+ public:
+ int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
+ int area = calc_area(ax1, ay1, ax2, ay2) + calc_area(bx1, by1, bx2, by2);
+ int x1, x2, y1, y2;
+ x1 = max(ax1, bx1);
+ x2 = min(ax2, bx2);
+ y1 = max(ay1, by1);
+ y2 = min(ay2, by2);
+ if (x2 - x1 > 0 && y2 - y1 > 0)
+ return area - calc_area(x1, y1, x2, y2);
+ else
+ return area;
+ }
};
diff --git a/Problems/0225.cpp b/Problems/0225.cpp
@@ -1,22 +1,22 @@
class MyStack {
- queue<int> q;
+ queue<int> q;
-public:
- void push(int x) {
- q.push(x);
- for (int i = 0; i < q.size() - 1; i++) {
- q.push(q.front());
- q.pop();
+ public:
+ void push(int x) {
+ q.push(x);
+ for (int i = 0; i < q.size() - 1; i++) {
+ q.push(q.front());
+ q.pop();
+ }
}
- }
- int pop() {
- int x = q.front();
- q.pop();
- return x;
- }
+ int pop() {
+ int x = q.front();
+ q.pop();
+ return x;
+ }
- int top() { return q.front(); }
- bool empty() { return q.empty(); }
+ int top() { return q.front(); }
+ bool empty() { return q.empty(); }
};
diff --git a/Problems/0226.cpp b/Problems/0226.cpp
@@ -1,17 +1,17 @@
class Solution {
-public:
- TreeNode *invertTree(TreeNode *root) {
- if (!root) return nullptr;
+ public:
+ TreeNode *invertTree(TreeNode *root) {
+ if (!root) return nullptr;
- stack<TreeNode *> st;
- st.push(root);
- while (!st.empty()) {
- TreeNode *root = st.top();
- st.pop();
- swap(root->left, root->right);
- if (root->left) st.push(root->left);
- if (root->right) st.push(root->right);
+ stack<TreeNode *> st;
+ st.push(root);
+ while (!st.empty()) {
+ TreeNode *root = st.top();
+ st.pop();
+ swap(root->left, root->right);
+ if (root->left) st.push(root->left);
+ if (root->right) st.push(root->right);
+ }
+ return root;
}
- return root;
- }
};
diff --git a/Problems/0227.cpp b/Problems/0227.cpp
@@ -1,19 +1,19 @@
class Solution {
-public:
- int calculate(string s) {
- stringstream ss("+" + s);
- char op;
- int n, last, ans = 0;
- while (ss >> op >> n) {
- if (op == '+' || op == '-') {
- n = op == '+' ? n : -n;
- ans += n;
- } else {
- n = op == '*' ? last * n : last / n;
- ans = ans - last + n;
- }
- last = n;
+ public:
+ int calculate(string s) {
+ stringstream ss("+" + s);
+ char op;
+ int n, last, ans = 0;
+ while (ss >> op >> n) {
+ if (op == '+' || op == '-') {
+ n = op == '+' ? n : -n;
+ ans += n;
+ } else {
+ n = op == '*' ? last * n : last / n;
+ ans = ans - last + n;
+ }
+ last = n;
+ }
+ return ans;
}
- return ans;
- }
};
diff --git a/Problems/0228.cpp b/Problems/0228.cpp
@@ -1,22 +1,22 @@
class Solution {
-public:
- vector<string> summaryRanges(vector<int> &nums) {
- if (!nums.size()) return {};
- vector<string> res;
- int start = 0;
- for (int i = 1; i < nums.size(); i++) {
- if (nums[i] == nums[i - 1] + 1) continue;
- if (i - start > 1)
- res.push_back(to_string(nums[start]) + "->" + to_string(nums[i - 1]));
- else
- res.push_back(to_string(nums[start]));
- start = i;
- }
- if (nums.size() - start > 1)
- res.push_back(to_string(nums[start]) + "->" + to_string(nums.back()));
- else
- res.push_back(to_string(nums[start]));
+ public:
+ vector<string> summaryRanges(vector<int> &nums) {
+ if (!nums.size()) return {};
+ vector<string> res;
+ int start = 0;
+ for (int i = 1; i < nums.size(); i++) {
+ if (nums[i] == nums[i - 1] + 1) continue;
+ if (i - start > 1)
+ res.push_back(to_string(nums[start]) + "->" + to_string(nums[i - 1]));
+ else
+ res.push_back(to_string(nums[start]));
+ start = i;
+ }
+ if (nums.size() - start > 1)
+ res.push_back(to_string(nums[start]) + "->" + to_string(nums.back()));
+ else
+ res.push_back(to_string(nums[start]));
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0230.cpp b/Problems/0230.cpp
@@ -1,17 +1,17 @@
class Solution {
-public:
- int kthSmallest(TreeNode *root, int k) {
- stack<TreeNode *> st;
- while (true) {
- while (root) {
- st.push(root);
- root = root->left;
- }
- if (st.empty()) break;
- root = st.top(), st.pop();
- if (!--k) return root->val;
- root = root->right;
+ public:
+ int kthSmallest(TreeNode *root, int k) {
+ stack<TreeNode *> st;
+ while (true) {
+ while (root) {
+ st.push(root);
+ root = root->left;
+ }
+ if (st.empty()) break;
+ root = st.top(), st.pop();
+ if (!--k) return root->val;
+ root = root->right;
+ }
+ return -1;
}
- return -1;
- }
};
diff --git a/Problems/0231.cpp b/Problems/0231.cpp
@@ -1,4 +1,4 @@
class Solution {
-public:
- bool isPowerOfTwo(int n) { return n > 0 && !(n & (n - 1)); }
+ public:
+ bool isPowerOfTwo(int n) { return n > 0 && !(n & (n - 1)); }
};
diff --git a/Problems/0232.cpp b/Problems/0232.cpp
@@ -1 +1 @@
-Formating: Problems/0232.cpp
+Formating : Problems / 0232.cpp
diff --git a/Problems/0234.cpp b/Problems/0234.cpp
@@ -1,38 +1,38 @@
class Solution {
-public:
- ListNode *invert(ListNode *head) {
- ListNode *p, *q, *r;
+ public:
+ ListNode *invert(ListNode *head) {
+ ListNode *p, *q, *r;
- p = head;
- q = nullptr;
- while (p) {
- r = q;
- q = p;
- p = p->next;
- q->next = r;
+ p = head;
+ q = nullptr;
+ while (p) {
+ r = q;
+ q = p;
+ p = p->next;
+ q->next = r;
+ }
+ return q;
}
- return q;
- }
- ListNode *first_half_end(ListNode *head) {
- ListNode *fast, *slow;
- fast = slow = head;
- while (fast->next && fast->next->next) {
- fast = fast->next->next;
- slow = slow->next;
+ ListNode *first_half_end(ListNode *head) {
+ ListNode *fast, *slow;
+ fast = slow = head;
+ while (fast->next && fast->next->next) {
+ fast = fast->next->next;
+ slow = slow->next;
+ }
+ return slow;
}
- return slow;
- }
- bool isPalindrome(ListNode *head) {
- if (!head || !head->next) return true;
+ bool isPalindrome(ListNode *head) {
+ if (!head || !head->next) return true;
- ListNode *fhe = first_half_end(head);
- ListNode *shs = invert(fhe->next);
+ ListNode *fhe = first_half_end(head);
+ ListNode *shs = invert(fhe->next);
- for (ListNode *p = head, *tmp = shs; tmp; p = p->next, tmp = tmp->next)
- if (p->val != tmp->val) return false;
+ for (ListNode *p = head, *tmp = shs; tmp; p = p->next, tmp = tmp->next)
+ if (p->val != tmp->val) return false;
- return true;
- }
+ return true;
+ }
};
diff --git a/Problems/0235.cpp b/Problems/0235.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
- TreeNode *tmp = root;
- while (true) {
- if (root->val > p->val && root->val > q->val)
- root = root->left;
- else if (root->val < p->val && root->val < q->val)
- root = root->right;
- else
- break;
+ public:
+ TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
+ TreeNode *tmp = root;
+ while (true) {
+ if (root->val > p->val && root->val > q->val)
+ root = root->left;
+ else if (root->val < p->val && root->val < q->val)
+ root = root->right;
+ else
+ break;
+ }
+ return root;
}
- return root;
- }
};
diff --git a/Problems/0236.cpp b/Problems/0236.cpp
@@ -1,30 +1,32 @@
class Solution {
-public:
- TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
- unordered_map<TreeNode *, TreeNode *> um;
- stack<TreeNode *> st;
- st.push(root);
- while (!st.empty()) {
- TreeNode *root = st.top();
- st.pop();
- if (root->left) {
- um.insert({root->left, root});
- st.push(root->left);
- }
- if (root->right) {
- um.insert({root->right, root});
- st.push(root->right);
- }
- }
+ public:
+ TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
+ unordered_map<TreeNode *, TreeNode *> um;
+ stack<TreeNode *> st;
+ st.push(root);
+ while (!st.empty()) {
+ TreeNode *root = st.top();
+ st.pop();
+ if (root->left) {
+ um.insert({root->left, root});
+ st.push(root->left);
+ }
+ if (root->right) {
+ um.insert({root->right, root});
+ st.push(root->right);
+ }
+ }
- unordered_set<TreeNode *> ans;
- while (p) {
- ans.insert(p);
- p = um[p];
- }
+ unordered_set<TreeNode *> ans;
+ while (p) {
+ ans.insert(p);
+ p = um[p];
+ }
- while (!ans.count(q)) { q = um[q]; }
+ while (!ans.count(q)) {
+ q = um[q];
+ }
- return q;
- }
+ return q;
+ }
};
diff --git a/Problems/0237.cpp b/Problems/0237.cpp
@@ -1,7 +1,7 @@
class Solution {
-public:
- void deleteNode(ListNode *node) {
- node->val = node->next->val;
- node->next = node->next->next;
- }
+ public:
+ void deleteNode(ListNode *node) {
+ node->val = node->next->val;
+ node->next = node->next->next;
+ }
};
diff --git a/Problems/0238.cpp b/Problems/0238.cpp
@@ -1,17 +1,17 @@
class Solution {
-public:
- vector<int> productExceptSelf(vector<int> &nums) {
- int n = nums.size();
- vector<int> answer(n, 1);
+ public:
+ vector<int> productExceptSelf(vector<int> &nums) {
+ int n = nums.size();
+ vector<int> answer(n, 1);
- int acc1 = 1, acc2 = 1;
- for (int i = 0, j = n - 1; i < n; i++, j--) {
- answer[i] *= acc1;
- answer[j] *= acc2;
- acc1 *= nums[i];
- acc2 *= nums[j];
- }
+ int acc1 = 1, acc2 = 1;
+ for (int i = 0, j = n - 1; i < n; i++, j--) {
+ answer[i] *= acc1;
+ answer[j] *= acc2;
+ acc1 *= nums[i];
+ acc2 *= nums[j];
+ }
- return answer;
- }
+ return answer;
+ }
};
diff --git a/Problems/0239.cpp b/Problems/0239.cpp
@@ -1,17 +1,19 @@
class Solution {
-public:
- vector<int> maxSlidingWindow(vector<int> &nums, int k) {
- int n = nums.size();
- vector<int> res;
- deque<int> q;
+ public:
+ vector<int> maxSlidingWindow(vector<int> &nums, int k) {
+ int n = nums.size();
+ vector<int> res;
+ deque<int> q;
- res.reserve(n - k + 1);
- for (int i = 0; i < n; i++) {
- while (!q.empty() && q.front() < i - k + 1) q.pop_front();
- while (!q.empty() && nums[q.back()] < nums[i]) q.pop_back();
- q.push_back(i);
- if (i >= k - 1) res.push_back(nums[q.front()]);
+ res.reserve(n - k + 1);
+ for (int i = 0; i < n; i++) {
+ while (!q.empty() && q.front() < i - k + 1)
+ q.pop_front();
+ while (!q.empty() && nums[q.back()] < nums[i])
+ q.pop_back();
+ q.push_back(i);
+ if (i >= k - 1) res.push_back(nums[q.front()]);
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0240.cpp b/Problems/0240.cpp
@@ -1,14 +1,14 @@
class Solution {
-public:
- bool searchMatrix(vector<vector<int>> &matrix, int target) {
- int n = matrix.size(), m = matrix[0].size(), x = 0, y = m - 1;
- while (x < n && y >= 0) {
- if (matrix[x][y] == target) return true;
- if (matrix[x][y] > target)
- y--;
- else
- x++;
+ public:
+ bool searchMatrix(vector<vector<int>> &matrix, int target) {
+ int n = matrix.size(), m = matrix[0].size(), x = 0, y = m - 1;
+ while (x < n && y >= 0) {
+ if (matrix[x][y] == target) return true;
+ if (matrix[x][y] > target)
+ y--;
+ else
+ x++;
+ }
+ return false;
}
- return false;
- }
};
diff --git a/Problems/0241.cpp b/Problems/0241.cpp
@@ -1,27 +1,25 @@
class Solution {
- int operate(char op, int a, int b) {
- switch (op) {
- case '+': return a + b;
- case '-': return a - b;
- case '*': return a * b;
+ int operate(char op, int a, int b) {
+ switch (op) {
+ case '+': return a + b;
+ case '-': return a - b;
+ case '*': return a * b;
+ }
+ return 0;
}
- return 0;
- }
- vector<int> rec(const string &expression, int start, int end) {
- vector<int> res;
- for (int i = start; i < end; i++) {
- if (isdigit(expression[i])) continue;
- for (auto n1 : rec(expression, start, i))
- for (auto n2 : rec(expression, i + 1, end))
- res.push_back(operate(expression[i], n1, n2));
+ vector<int> rec(const string &expression, int start, int end) {
+ vector<int> res;
+ for (int i = start; i < end; i++) {
+ if (isdigit(expression[i])) continue;
+ for (auto n1 : rec(expression, start, i))
+ for (auto n2 : rec(expression, i + 1, end))
+ res.push_back(operate(expression[i], n1, n2));
+ }
+ if (res.empty()) return {stoi(expression.substr(start, end - start))};
+ return res;
}
- if (res.empty()) return {stoi(expression.substr(start, end - start))};
- return res;
- }
-public:
- vector<int> diffWaysToCompute(const string &expression) {
- return rec(expression, 0, expression.size());
- }
+ public:
+ vector<int> diffWaysToCompute(const string &expression) { return rec(expression, 0, expression.size()); }
};
diff --git a/Problems/0242.cpp b/Problems/0242.cpp
@@ -1,14 +1,15 @@
class Solution {
-public:
- bool isAnagram(string s, string t) {
- if (s.size() != t.size()) return false;
- vector<int> um(26, 0);
- for (char c : s) um[c - 'a']++;
- for (char c : t)
- if (!um[c - 'a'])
- return false;
- else
- um[c - 'a']--;
- return true;
- }
+ public:
+ bool isAnagram(string s, string t) {
+ if (s.size() != t.size()) return false;
+ vector<int> um(26, 0);
+ for (char c : s)
+ um[c - 'a']++;
+ for (char c : t)
+ if (!um[c - 'a'])
+ return false;
+ else
+ um[c - 'a']--;
+ return true;
+ }
};
diff --git a/Problems/0257.cpp b/Problems/0257.cpp
@@ -1,24 +1,23 @@
class Solution {
-public:
- vector<string> binaryTreePaths(TreeNode *root) {
- if (!root) return {};
+ public:
+ vector<string> binaryTreePaths(TreeNode *root) {
+ if (!root) return {};
- vector<string> res;
- stack<pair<TreeNode *, string>> st;
- st.push({root, to_string(root->val)});
- while (!st.empty()) {
- TreeNode *root = st.top().first;
- string s = st.top().second;
- st.pop();
- if (!root->left && !root->right)
- res.push_back(s);
- else {
- s += "->";
- if (root->left) st.push({root->left, s + to_string(root->left->val)});
- if (root->right)
- st.push({root->right, s + to_string(root->right->val)});
- }
+ vector<string> res;
+ stack<pair<TreeNode *, string>> st;
+ st.push({root, to_string(root->val)});
+ while (!st.empty()) {
+ TreeNode *root = st.top().first;
+ string s = st.top().second;
+ st.pop();
+ if (!root->left && !root->right)
+ res.push_back(s);
+ else {
+ s += "->";
+ if (root->left) st.push({root->left, s + to_string(root->left->val)});
+ if (root->right) st.push({root->right, s + to_string(root->right->val)});
+ }
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0258.cpp b/Problems/0258.cpp
@@ -1,11 +1,13 @@
class Solution {
-public:
- int addDigits(int num) {
- while (num >= 10) {
- int sum = 0;
- do { sum += num % 10; } while ((num /= 10) > 0);
- num = sum;
+ public:
+ int addDigits(int num) {
+ while (num >= 10) {
+ int sum = 0;
+ do {
+ sum += num % 10;
+ } while ((num /= 10) > 0);
+ num = sum;
+ }
+ return num;
}
- return num;
- }
};
diff --git a/Problems/0263.cpp b/Problems/0263.cpp
@@ -1,10 +1,11 @@
class Solution {
-public:
- bool isUgly(int n) {
- if (n <= 0) return false;
- for (auto i : {2, 3, 5})
- while (n % i == 0) n /= i;
+ public:
+ bool isUgly(int n) {
+ if (n <= 0) return false;
+ for (auto i : {2, 3, 5})
+ while (n % i == 0)
+ n /= i;
- return n == 1;
- }
+ return n == 1;
+ }
};
diff --git a/Problems/0264.cpp b/Problems/0264.cpp
@@ -1,41 +1,41 @@
// Brute force solution
class Solution {
-public:
- int nthUglyNumber(int n) {
- priority_queue<long long, vector<long long>, greater<long long>> pq;
- unordered_set<long long> us;
- int count;
+ public:
+ int nthUglyNumber(int n) {
+ priority_queue<long long, vector<long long>, greater<long long>> pq;
+ unordered_set<long long> us;
+ int count;
- pq.push(1);
- count = 1;
- while (!pq.empty() && count < n) {
- long long n = pq.top();
- pq.pop();
- for (int i : {2, 3, 5}) {
- if (us.count(n * i)) continue;
- pq.push(n * i);
- us.insert(n * i);
- }
- count++;
- }
+ pq.push(1);
+ count = 1;
+ while (!pq.empty() && count < n) {
+ long long n = pq.top();
+ pq.pop();
+ for (int i : {2, 3, 5}) {
+ if (us.count(n * i)) continue;
+ pq.push(n * i);
+ us.insert(n * i);
+ }
+ count++;
+ }
- return (int)pq.top();
- }
+ return (int)pq.top();
+ }
};
// DP solution
class Solution {
-public:
- int nthUglyNumber(int n) {
- vector<int> k(n);
- k[0] = 1;
- int t2 = 0, t3 = 0, t5 = 0;
- for (int i = 1; i < n; i++) {
- k[i] = min(k[t2] * 2, min(k[t3] * 3, k[t5] * 5));
- t2 += k[i] == k[t2] * 2;
- t3 += k[i] == k[t3] * 3;
- t5 += k[i] == k[t5] * 5;
+ public:
+ int nthUglyNumber(int n) {
+ vector<int> k(n);
+ k[0] = 1;
+ int t2 = 0, t3 = 0, t5 = 0;
+ for (int i = 1; i < n; i++) {
+ k[i] = min(k[t2] * 2, min(k[t3] * 3, k[t5] * 5));
+ t2 += k[i] == k[t2] * 2;
+ t3 += k[i] == k[t3] * 3;
+ t5 += k[i] == k[t5] * 5;
+ }
+ return k.back();
}
- return k.back();
- }
};
diff --git a/Problems/0268.cpp b/Problems/0268.cpp
@@ -1,8 +1,9 @@
class Solution {
-public:
- int missingNumber(vector<int> &nums) {
- int res = nums.size();
- for (int i = 0; i < nums.size(); i++) res ^= i ^ nums[i];
- return res;
- }
+ public:
+ int missingNumber(vector<int> &nums) {
+ int res = nums.size();
+ for (int i = 0; i < nums.size(); i++)
+ res ^= i ^ nums[i];
+ return res;
+ }
};
diff --git a/Problems/0274.cpp b/Problems/0274.cpp
@@ -1,19 +1,20 @@
class Solution {
- static int arr[5001];
+ static int arr[5001];
-public:
- int hIndex(vector<int> &citations) {
- memset(arr, 0x00, sizeof(arr));
- for (int n : citations) arr[n]++;
+ public:
+ int hIndex(vector<int> &citations) {
+ memset(arr, 0x00, sizeof(arr));
+ for (int n : citations)
+ arr[n]++;
- int total = 0;
- for (int i = 5000; i >= 0; i--) {
- total += arr[i];
- if (total >= i) return i;
- }
+ int total = 0;
+ for (int i = 5000; i >= 0; i--) {
+ total += arr[i];
+ if (total >= i) return i;
+ }
- return -1;
- }
+ return -1;
+ }
};
int Solution::arr[5001] = {0};
diff --git a/Problems/0278.cpp b/Problems/0278.cpp
@@ -2,16 +2,16 @@
// bool isBadVersion(int version);
class Solution {
-public:
- int firstBadVersion(int n) {
- int low = 1, high = n, last = -1;
- while (low <= high) {
- int mid = low + (high - low) / 2;
- if (isBadVersion(mid))
- high = (last = mid) - 1;
- else
- low = mid + 1;
+ public:
+ int firstBadVersion(int n) {
+ int low = 1, high = n, last = -1;
+ while (low <= high) {
+ int mid = low + (high - low) / 2;
+ if (isBadVersion(mid))
+ high = (last = mid) - 1;
+ else
+ low = mid + 1;
+ }
+ return last;
}
- return last;
- }
};
diff --git a/Problems/0279.cpp b/Problems/0279.cpp
@@ -1,16 +1,17 @@
class Solution {
-public:
- int numSquares(int n) {
- vector<int> dp(n + 1, INT_MAX - 1);
- vector<int> primes;
+ public:
+ int numSquares(int n) {
+ vector<int> dp(n + 1, INT_MAX - 1);
+ vector<int> primes;
- for (int i = 1; i <= sqrt(n); i++) primes.push_back(i * i);
+ for (int i = 1; i <= sqrt(n); i++)
+ primes.push_back(i * i);
- dp[0] = 0;
- for (int i = 1; i <= n; i++)
- for (int j = 0; j < primes.size() && primes[j] <= i; j++)
- dp[i] = min(dp[i], dp[i - primes[j]] + 1);
+ dp[0] = 0;
+ for (int i = 1; i <= n; i++)
+ for (int j = 0; j < primes.size() && primes[j] <= i; j++)
+ dp[i] = min(dp[i], dp[i - primes[j]] + 1);
- return dp[n];
- }
+ return dp[n];
+ }
};
diff --git a/Problems/0283.cpp b/Problems/0283.cpp
@@ -1,10 +1,11 @@
class Solution {
-public:
- void moveZeroes(vector<int> &nums) {
- int j = 0;
- for (int i = 0; i < nums.size(); i++)
- if (nums[i] != 0) nums[j++] = nums[i];
+ public:
+ void moveZeroes(vector<int> &nums) {
+ int j = 0;
+ for (int i = 0; i < nums.size(); i++)
+ if (nums[i] != 0) nums[j++] = nums[i];
- while (j < nums.size()) nums[j++] = 0;
- }
+ while (j < nums.size())
+ nums[j++] = 0;
+ }
};
diff --git a/Problems/0287.cpp b/Problems/0287.cpp
@@ -1,18 +1,18 @@
class Solution {
-public:
- int findDuplicate(vector<int> &nums) {
- int slow = 0, fast = 0;
- while (true) {
- fast = nums[nums[fast]];
- slow = nums[slow];
- if (fast == slow) {
- fast = 0;
- while (fast != slow) {
- fast = nums[fast];
- slow = nums[slow];
+ public:
+ int findDuplicate(vector<int> &nums) {
+ int slow = 0, fast = 0;
+ while (true) {
+ fast = nums[nums[fast]];
+ slow = nums[slow];
+ if (fast == slow) {
+ fast = 0;
+ while (fast != slow) {
+ fast = nums[fast];
+ slow = nums[slow];
+ }
+ return fast;
+ }
}
- return fast;
- }
}
- }
};
diff --git a/Problems/0289.cpp b/Problems/0289.cpp
@@ -1,22 +1,22 @@
class Solution {
-public:
- void gameOfLife(vector<vector<int>> &board) {
- int n = board.size(), m = board[0].size();
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < m; j++) {
- int add = (board[i][j] & 1) << 1;
- for (int k = max(i - 1, 0); k <= min(n - 1, i + 1); k++) {
- for (int l = max(j - 1, 0); l <= min(m - 1, j + 1); l++) {
- board[k][l] += add;
- }
+ public:
+ void gameOfLife(vector<vector<int>> &board) {
+ int n = board.size(), m = board[0].size();
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < m; j++) {
+ int add = (board[i][j] & 1) << 1;
+ for (int k = max(i - 1, 0); k <= min(n - 1, i + 1); k++) {
+ for (int l = max(j - 1, 0); l <= min(m - 1, j + 1); l++) {
+ board[k][l] += add;
+ }
+ }
+ }
}
- }
- }
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < m; j++) {
- board[i][j] = board[i][j] == 7 || board[i][j] == 9 || board[i][j] == 6;
- }
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < m; j++) {
+ board[i][j] = board[i][j] == 7 || board[i][j] == 9 || board[i][j] == 6;
+ }
+ }
}
- }
};
diff --git a/Problems/0290.cpp b/Problems/0290.cpp
@@ -1,22 +1,22 @@
class Solution {
-public:
- bool wordPattern(string pattern, string s) {
- vector<string> done(26, "");
- unordered_set<string> st;
+ public:
+ bool wordPattern(string pattern, string s) {
+ vector<string> done(26, "");
+ unordered_set<string> st;
- int c = 0;
- istringstream in(s);
- for (string crnt; in >> crnt; ++c) {
- if (c >= pattern.size()) return false;
- int index = pattern[c] - 'a';
- if (done[index].empty()) {
- if (st.count(crnt)) return false;
- st.insert(done[index] = crnt);
- } else if (done[index] != crnt)
- return false;
- }
- if (pattern.size() > c) return false;
+ int c = 0;
+ istringstream in(s);
+ for (string crnt; in >> crnt; ++c) {
+ if (c >= pattern.size()) return false;
+ int index = pattern[c] - 'a';
+ if (done[index].empty()) {
+ if (st.count(crnt)) return false;
+ st.insert(done[index] = crnt);
+ } else if (done[index] != crnt)
+ return false;
+ }
+ if (pattern.size() > c) return false;
- return true;
- }
+ return true;
+ }
};
diff --git a/Problems/0292.cpp b/Problems/0292.cpp
@@ -1,4 +1,4 @@
class Solution {
-public:
- bool canWinNim(int n) { return n % 4; }
+ public:
+ bool canWinNim(int n) { return n % 4; }
};
diff --git a/Problems/0295.cpp b/Problems/0295.cpp
@@ -1,31 +1,31 @@
class MedianFinder {
- priority_queue<int> left;
- priority_queue<int, vector<int>, greater<int>> right;
+ priority_queue<int> left;
+ priority_queue<int, vector<int>, greater<int>> right;
-public:
- void addNum(int num) {
- if (left.empty() || num < left.top())
- left.push(num);
- else
- right.push(num);
+ public:
+ void addNum(int num) {
+ if (left.empty() || num < left.top())
+ left.push(num);
+ else
+ right.push(num);
- if (left.size() < right.size()) {
- int temp = right.top();
- right.pop();
- left.push(temp);
- }
+ if (left.size() < right.size()) {
+ int temp = right.top();
+ right.pop();
+ left.push(temp);
+ }
- if (left.size() - right.size() > 1) {
- int temp = left.top();
- left.pop();
- right.push(temp);
+ if (left.size() - right.size() > 1) {
+ int temp = left.top();
+ left.pop();
+ right.push(temp);
+ }
}
- }
- double findMedian() {
- if (left.size() > right.size())
- return left.top();
- else
- return (left.top() + right.top()) * 0.5;
- }
+ double findMedian() {
+ if (left.size() > right.size())
+ return left.top();
+ else
+ return (left.top() + right.top()) * 0.5;
+ }
};
diff --git a/Problems/0297.cpp b/Problems/0297.cpp
@@ -1,41 +1,41 @@
class Codec {
-public:
- string serialize(TreeNode *root) {
- ostringstream out;
- serialize(root, out);
- return out.str();
- }
+ public:
+ string serialize(TreeNode *root) {
+ ostringstream out;
+ serialize(root, out);
+ return out.str();
+ }
- TreeNode *deserialize(string data) {
- istringstream in(data);
- return deserialize(in);
- }
+ TreeNode *deserialize(string data) {
+ istringstream in(data);
+ return deserialize(in);
+ }
-private:
- void serialize(TreeNode *root, ostringstream &out) {
- stack<TreeNode *> st;
+ private:
+ void serialize(TreeNode *root, ostringstream &out) {
+ stack<TreeNode *> st;
- st.push(root);
- while (!st.empty()) {
- TreeNode *root = st.top();
- st.pop();
- if (!root)
- out << "# ";
- else {
- out << root->val << ' ';
- st.push(root->right);
- st.push(root->left);
- }
+ st.push(root);
+ while (!st.empty()) {
+ TreeNode *root = st.top();
+ st.pop();
+ if (!root)
+ out << "# ";
+ else {
+ out << root->val << ' ';
+ st.push(root->right);
+ st.push(root->left);
+ }
+ }
}
- }
- TreeNode *deserialize(istringstream &in) {
- string val;
- in >> val;
- if (val == "#") return nullptr;
- TreeNode *root = new TreeNode(stoi(val));
- root->left = deserialize(in);
- root->right = deserialize(in);
- return root;
- }
+ TreeNode *deserialize(istringstream &in) {
+ string val;
+ in >> val;
+ if (val == "#") return nullptr;
+ TreeNode *root = new TreeNode(stoi(val));
+ root->left = deserialize(in);
+ root->right = deserialize(in);
+ return root;
+ }
};
diff --git a/Problems/0299.cpp b/Problems/0299.cpp
@@ -1,21 +1,21 @@
class Solution {
-public:
- string getHint(string secret, string guess) {
- int n = secret.size(), cows = 0, bulls = 0;
- unordered_map<char, int> ums;
- for (int i = 0; i < n; i++)
- if (guess[i] == secret[i])
- bulls++;
- else
- ums[secret[i]]++;
+ public:
+ string getHint(string secret, string guess) {
+ int n = secret.size(), cows = 0, bulls = 0;
+ unordered_map<char, int> ums;
+ for (int i = 0; i < n; i++)
+ if (guess[i] == secret[i])
+ bulls++;
+ else
+ ums[secret[i]]++;
- for (int i = 0; i < n; i++) {
- if (guess[i] == secret[i])
- continue;
- else if (ums[guess[i]] > 0)
- cows++;
- ums[guess[i]]--;
+ for (int i = 0; i < n; i++) {
+ if (guess[i] == secret[i])
+ continue;
+ else if (ums[guess[i]] > 0)
+ cows++;
+ ums[guess[i]]--;
+ }
+ return to_string(bulls) + "A" + to_string(cows) + "B";
}
- return to_string(bulls) + "A" + to_string(cows) + "B";
- }
};
diff --git a/Problems/0300.cpp b/Problems/0300.cpp
@@ -1,3 +1 @@
-Formating: Problems/0152.cpp
-Formating: Problems/0300.cpp
-Formating: Problems/1567.cpp
+Formating : Problems / 0152.cpp Formating : Problems / 0300.cpp Formating : Problems / 1567.cpp
diff --git a/Problems/0304.cpp b/Problems/0304.cpp
@@ -1,26 +1,26 @@
class NumMatrix {
- int n, m;
- vector<vector<int>> dp;
+ int n, m;
+ vector<vector<int>> dp;
-public:
- NumMatrix(vector<vector<int>> &matrix)
- : n(matrix.size()), m(matrix[0].size()),
- dp(vector<vector<int>>(n, vector<int>(m, 0))) {
- for (int i = 0, sum = 0; i < n; i++) sum = dp[i][0] = matrix[i][0] + sum;
- for (int i = 0, sum = 0; i < m; i++) sum = dp[0][i] = matrix[0][i] + sum;
- for (int i = 1; i < n; i++) {
- for (int j = 1; j < m; j++) {
- dp[i][j] =
- matrix[i][j] + dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1];
- }
+ public:
+ NumMatrix(vector<vector<int>> &matrix)
+ : n(matrix.size()), m(matrix[0].size()), dp(vector<vector<int>>(n, vector<int>(m, 0))) {
+ for (int i = 0, sum = 0; i < n; i++)
+ sum = dp[i][0] = matrix[i][0] + sum;
+ for (int i = 0, sum = 0; i < m; i++)
+ sum = dp[0][i] = matrix[0][i] + sum;
+ for (int i = 1; i < n; i++) {
+ for (int j = 1; j < m; j++) {
+ dp[i][j] = matrix[i][j] + dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1];
+ }
+ }
}
- }
- int sumRegion(int x1, int y1, int x2, int y2) {
- int res = dp[x2][y2];
- if (x1 > 0) res -= dp[x1 - 1][y2];
- if (y1 > 0) res -= dp[x2][y1 - 1];
- if (x1 > 0 && y1 > 0) res += dp[x1 - 1][y1 - 1];
- return res;
- }
+ int sumRegion(int x1, int y1, int x2, int y2) {
+ int res = dp[x2][y2];
+ if (x1 > 0) res -= dp[x1 - 1][y2];
+ if (y1 > 0) res -= dp[x2][y1 - 1];
+ if (x1 > 0 && y1 > 0) res += dp[x1 - 1][y1 - 1];
+ return res;
+ }
};
diff --git a/Problems/0306.cpp b/Problems/0306.cpp
@@ -1,26 +1,25 @@
class Solution {
-public:
- bool isAdditiveNumber(const string &num) {
- for (int i = 1; i < num.size(); i++) {
- long num1 = stol(num.substr(0, i));
- for (int j = i + 1; j < num.size(); j++) {
- long n1 = num1, n2 = stol(num.substr(i, j - i)), n3;
- int next = j;
- while (next < num.size()) {
- const string pre = to_string(n3 = n1 + n2);
+ public:
+ bool isAdditiveNumber(const string &num) {
+ for (int i = 1; i < num.size(); i++) {
+ long num1 = stol(num.substr(0, i));
+ for (int j = i + 1; j < num.size(); j++) {
+ long n1 = num1, n2 = stol(num.substr(i, j - i)), n3;
+ int next = j;
+ while (next < num.size()) {
+ const string pre = to_string(n3 = n1 + n2);
- auto res =
- std::mismatch(pre.begin(), pre.end(), num.substr(next).begin());
- if (res.first != pre.end()) break;
+ auto res = std::mismatch(pre.begin(), pre.end(), num.substr(next).begin());
+ if (res.first != pre.end()) break;
- next += pre.size();
- n1 = n2, n2 = n3;
+ next += pre.size();
+ n1 = n2, n2 = n3;
+ }
+ if (next == num.size()) return true;
+ if (num[i] == '0') break;
+ }
+ if (num[0] == '0') break;
}
- if (next == num.size()) return true;
- if (num[i] == '0') break;
- }
- if (num[0] == '0') break;
+ return false;
}
- return false;
- }
};
diff --git a/Problems/0309.cpp b/Problems/0309.cpp
@@ -1,2 +1 @@
-Formating: Problems/0309.cpp
-Formating: Problems/0714.cpp
+Formating : Problems / 0309.cpp Formating : Problems / 0714.cpp
diff --git a/Problems/0310.cpp b/Problems/0310.cpp
@@ -1,37 +1,37 @@
class Solution {
-public:
- vector<int> findMinHeightTrees(int n, vector<vector<int>> &edges) {
- if (n == 0) return {};
- if (n == 1) return {0};
- if (n == 2) return {0, 1};
+ public:
+ vector<int> findMinHeightTrees(int n, vector<vector<int>> &edges) {
+ if (n == 0) return {};
+ if (n == 1) return {0};
+ if (n == 2) return {0, 1};
- vector<set<int>> adj(n);
- vector<int> count(n);
+ vector<set<int>> adj(n);
+ vector<int> count(n);
- for (auto &e : edges) {
- adj[e[0]].insert(e[1]);
- adj[e[1]].insert(e[0]);
- count[e[0]]++;
- count[e[1]]++;
- }
+ for (auto &e : edges) {
+ adj[e[0]].insert(e[1]);
+ adj[e[1]].insert(e[0]);
+ count[e[0]]++;
+ count[e[1]]++;
+ }
- queue<int> q;
- for (int i = 0; i < n; i++)
- if (count[i] == 1) q.push(i);
+ queue<int> q;
+ for (int i = 0; i < n; i++)
+ if (count[i] == 1) q.push(i);
- vector<int> res;
- while (!q.empty()) {
- res.clear();
- for (int k = q.size(); k > 0; k--) {
- int c = q.front();
- q.pop();
- res.push_back(c);
- for (int n : adj[c]) {
- if (--count[n] == 1) q.push(n);
+ vector<int> res;
+ while (!q.empty()) {
+ res.clear();
+ for (int k = q.size(); k > 0; k--) {
+ int c = q.front();
+ q.pop();
+ res.push_back(c);
+ for (int n : adj[c]) {
+ if (--count[n] == 1) q.push(n);
+ }
+ }
}
- }
- }
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0319.cpp b/Problems/0319.cpp
@@ -1,4 +1,4 @@
class Solution {
-public:
- int bulbSwitch(int n) { return sqrt(n); }
+ public:
+ int bulbSwitch(int n) { return sqrt(n); }
};
diff --git a/Problems/0322.cpp b/Problems/0322.cpp
@@ -1,16 +1,15 @@
// DP solution
class Solution {
-public:
- int coinChange(vector<int> &coins, int amount) {
- vector<int> dp(amount + 1, INT_MAX);
- dp[0] = 0;
+ public:
+ int coinChange(vector<int> &coins, int amount) {
+ vector<int> dp(amount + 1, INT_MAX);
+ dp[0] = 0;
- for (int i = 0; i < amount; i++) {
- if (dp[i] == INT_MAX) continue;
- for (int coin : coins)
- if ((long long)coin + i <= amount)
- dp[coin + i] = min(dp[coin + i], dp[i] + 1);
+ for (int i = 0; i < amount; i++) {
+ if (dp[i] == INT_MAX) continue;
+ for (int coin : coins)
+ if ((long long)coin + i <= amount) dp[coin + i] = min(dp[coin + i], dp[i] + 1);
+ }
+ return dp[amount] != INT_MAX ? dp[amount] : -1;
}
- return dp[amount] != INT_MAX ? dp[amount] : -1;
- }
};
diff --git a/Problems/0326.cpp b/Problems/0326.cpp
@@ -1,7 +1,7 @@
class Solution {
-public:
- bool isPowerOfThree(int n) {
- double x = log10(n) / log10(3);
- return n > 0 && x == round(x);
- }
+ public:
+ bool isPowerOfThree(int n) {
+ double x = log10(n) / log10(3);
+ return n > 0 && x == round(x);
+ }
};
diff --git a/Problems/0328.cpp b/Problems/0328.cpp
@@ -1,18 +1,18 @@
class Solution {
-public:
- ListNode *oddEvenList(ListNode *head) {
- if (!head) return nullptr;
+ public:
+ ListNode *oddEvenList(ListNode *head) {
+ if (!head) return nullptr;
- ListNode *h, *t, *p;
- t = h = new ListNode();
+ ListNode *h, *t, *p;
+ t = h = new ListNode();
- for (p = head; p && p->next;) {
- t = t->next = p->next;
- p->next = p->next->next;
- if (p->next) p = p->next;
+ for (p = head; p && p->next;) {
+ t = t->next = p->next;
+ p->next = p->next->next;
+ if (p->next) p = p->next;
+ }
+ p->next = h->next;
+ t->next = nullptr;
+ return head;
}
- p->next = h->next;
- t->next = nullptr;
- return head;
- }
};
diff --git a/Problems/0334.cpp b/Problems/0334.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- bool increasingTriplet(vector<int> &nums) {
- int a = INT_MAX, b = INT_MAX;
- for (int x : nums) {
- if (x <= a)
- a = x;
- else if (x <= b)
- b = x;
- else
- return true;
+ public:
+ bool increasingTriplet(vector<int> &nums) {
+ int a = INT_MAX, b = INT_MAX;
+ for (int x : nums) {
+ if (x <= a)
+ a = x;
+ else if (x <= b)
+ b = x;
+ else
+ return true;
+ }
+ return false;
}
- return false;
- }
};
diff --git a/Problems/0338.cpp b/Problems/0338.cpp
@@ -1,12 +1,12 @@
class Solution {
-public:
- vector<int> countBits(int n) {
- vector<int> res(n + 1);
- int offset = 1;
- for (int i = 1; i <= n; i++) {
- if (offset * 2 == i) offset *= 2;
- res[i] = (res[i - offset]) + 1;
+ public:
+ vector<int> countBits(int n) {
+ vector<int> res(n + 1);
+ int offset = 1;
+ for (int i = 1; i <= n; i++) {
+ if (offset * 2 == i) offset *= 2;
+ res[i] = (res[i - offset]) + 1;
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0342.cpp b/Problems/0342.cpp
@@ -1,6 +1,4 @@
class Solution {
-public:
- bool isPowerOfFour(int n) {
- return n > 0 && (n & (n - 1)) == 0 && (n - 1) % 3 == 0;
- }
+ public:
+ bool isPowerOfFour(int n) { return n > 0 && (n & (n - 1)) == 0 && (n - 1) % 3 == 0; }
};
diff --git a/Problems/0343.cpp b/Problems/0343.cpp
@@ -1,13 +1,13 @@
class Solution {
-public:
- int integerBreak(int n) {
- if (n == 2) return 1;
- if (n == 3) return 2;
+ public:
+ int integerBreak(int n) {
+ if (n == 2) return 1;
+ if (n == 3) return 2;
- if (n % 3 == 0)
- return pow(3, n / 3);
- else if (n % 3 == 1)
- return pow(3, n / 3 - 1) * 4;
- return pow(3, n / 3) * (n % 3);
- }
+ if (n % 3 == 0)
+ return pow(3, n / 3);
+ else if (n % 3 == 1)
+ return pow(3, n / 3 - 1) * 4;
+ return pow(3, n / 3) * (n % 3);
+ }
};
diff --git a/Problems/0344.cpp b/Problems/0344.cpp
@@ -1,7 +1,8 @@
class Solution {
-public:
- void reverseString(vector<char> &s) {
- int i = 0, j = (int)s.size() - 1;
- while (i < j) swap(s[i++], s[j--]);
- }
+ public:
+ void reverseString(vector<char> &s) {
+ int i = 0, j = (int)s.size() - 1;
+ while (i < j)
+ swap(s[i++], s[j--]);
+ }
};
diff --git a/Problems/0345.cpp b/Problems/0345.cpp
@@ -1,20 +1,22 @@
class Solution {
- bool is_vowel(char c) {
- c = tolower(c);
- return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
- }
+ bool is_vowel(char c) {
+ c = tolower(c);
+ return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
+ }
-public:
- string reverseVowels(string s) {
- int i = 0, j = size(s) - 1;
- while (i < j) {
- while (i < j && !is_vowel(s[i])) i++;
- while (i < j && !is_vowel(s[j])) j--;
- if (i >= j) break;
- swap(s[i], s[j]);
- i++;
- j--;
+ public:
+ string reverseVowels(string s) {
+ int i = 0, j = size(s) - 1;
+ while (i < j) {
+ while (i < j && !is_vowel(s[i]))
+ i++;
+ while (i < j && !is_vowel(s[j]))
+ j--;
+ if (i >= j) break;
+ swap(s[i], s[j]);
+ i++;
+ j--;
+ }
+ return s;
}
- return s;
- }
};
diff --git a/Problems/0347.cpp b/Problems/0347.cpp
@@ -1,29 +1,27 @@
struct elem {
- static void reset() { id_cnt = 0; }
- static int id_cnt;
- int id = id_cnt++, count = 0;
- void operator++(int) { count++; }
- friend bool operator<(const elem &e1, const elem &e2) {
- return e1.count > e2.count;
- }
- friend ostream &operator<<(ostream &os, const elem &e) {
- return os << e.id << ": " << e.count;
- }
+ static void reset() { id_cnt = 0; }
+ static int id_cnt;
+ int id = id_cnt++, count = 0;
+ void operator++(int) { count++; }
+ friend bool operator<(const elem &e1, const elem &e2) { return e1.count > e2.count; }
+ friend ostream &operator<<(ostream &os, const elem &e) { return os << e.id << ": " << e.count; }
};
int elem::id_cnt = 0;
class Solution {
- const int size = 20002;
- const int mod = 10000;
+ const int size = 20002;
+ const int mod = 10000;
-public:
- vector<int> topKFrequent(vector<int> &nums, int k) {
- elem::reset();
- vector<elem> um(size);
- for (int n : nums) um[n + mod]++;
- sort(um.begin(), um.end());
- vector<int> res;
- for (int i = 0; i < k; i++) res.push_back(um[i].id - mod);
- return res;
- }
+ public:
+ vector<int> topKFrequent(vector<int> &nums, int k) {
+ elem::reset();
+ vector<elem> um(size);
+ for (int n : nums)
+ um[n + mod]++;
+ sort(um.begin(), um.end());
+ vector<int> res;
+ for (int i = 0; i < k; i++)
+ res.push_back(um[i].id - mod);
+ return res;
+ }
};
diff --git a/Problems/0350.cpp b/Problems/0350.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- vector<int> intersect(vector<int> &nums1, vector<int> &nums2) {
- unordered_multiset<int> s(nums1.begin(), nums1.end());
+ public:
+ vector<int> intersect(vector<int> &nums1, vector<int> &nums2) {
+ unordered_multiset<int> s(nums1.begin(), nums1.end());
- vector<int> res;
- for (int n : nums2) {
- const auto it = s.find(n);
- if (it == s.end()) continue;
- s.erase(it);
- res.push_back(n);
+ vector<int> res;
+ for (int n : nums2) {
+ const auto it = s.find(n);
+ if (it == s.end()) continue;
+ s.erase(it);
+ res.push_back(n);
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0352.cpp b/Problems/0352.cpp
@@ -1 +1 @@
-Formating: Problems/0352.cpp
+Formating : Problems / 0352.cpp
diff --git a/Problems/0367.cpp b/Problems/0367.cpp
@@ -1,4 +1,4 @@
class Solution {
-public:
- bool isPerfectSquare(int num) { return pow((int)sqrt(num), 2) == num; }
+ public:
+ bool isPerfectSquare(int num) { return pow((int)sqrt(num), 2) == num; }
};
diff --git a/Problems/0371.cpp b/Problems/0371.cpp
@@ -1,12 +1,12 @@
class Solution {
-public:
- int getSum(int a, int b) {
- unsigned c;
- while (b) {
- c = a & b;
- a ^= b;
- b = c << 1;
+ public:
+ int getSum(int a, int b) {
+ unsigned c;
+ while (b) {
+ c = a & b;
+ a ^= b;
+ b = c << 1;
+ }
+ return a;
}
- return a;
- }
};
diff --git a/Problems/0373.cpp b/Problems/0373.cpp
@@ -1,23 +1,22 @@
class Solution {
- typedef tuple<int, int, int> tpl;
+ typedef tuple<int, int, int> tpl;
-public:
- vector<vector<int>> kSmallestPairs(const vector<int> &nums1,
- const vector<int> &nums2, int k) {
- priority_queue<tpl, vector<tpl>, greater<tpl>> pq;
- vector<vector<int>> res;
- res.reserve(k);
+ public:
+ vector<vector<int>> kSmallestPairs(const vector<int> &nums1, const vector<int> &nums2, int k) {
+ priority_queue<tpl, vector<tpl>, greater<tpl>> pq;
+ vector<vector<int>> res;
+ res.reserve(k);
- for (int i = 0; i < min(k, (int)nums1.size()); i++)
- pq.push({nums1[i] + nums2[0], i, 0});
+ for (int i = 0; i < min(k, (int)nums1.size()); i++)
+ pq.push({nums1[i] + nums2[0], i, 0});
- while (k-- && !pq.empty()) {
- auto [sum, i, j] = pq.top();
- pq.pop();
- res.push_back({nums1[i], nums2[j]});
- if (j == nums2.size() - 1) continue;
- pq.push({nums1[i] + nums2[j + 1], i, j + 1});
+ while (k-- && !pq.empty()) {
+ auto [sum, i, j] = pq.top();
+ pq.pop();
+ res.push_back({nums1[i], nums2[j]});
+ if (j == nums2.size() - 1) continue;
+ pq.push({nums1[i] + nums2[j + 1], i, j + 1});
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0374.cpp b/Problems/0374.cpp
@@ -1,16 +1,16 @@
class Solution {
-public:
- int guessNumber(int n) {
- int low = 1, high = n;
- while (true) {
- int mid = low + (high - low) / 2;
- switch (guess(mid)) {
- case 0: return mid;
- case 1: low = mid + 1; break;
- case -1: high = mid - 1; break;
- default: return -1;
- }
+ public:
+ int guessNumber(int n) {
+ int low = 1, high = n;
+ while (true) {
+ int mid = low + (high - low) / 2;
+ switch (guess(mid)) {
+ case 0: return mid;
+ case 1: low = mid + 1; break;
+ case -1: high = mid - 1; break;
+ default: return -1;
+ }
+ }
+ return -1;
}
- return -1;
- }
};
diff --git a/Problems/0376.cpp b/Problems/0376.cpp
@@ -1,14 +1,14 @@
class Solution {
-public:
- int wiggleMaxLength(vector<int> &nums) {
- if (nums.size() == 0) return 0;
- int up = 1, down = 1;
- for (int i = 1; i < nums.size(); i++) {
- if (nums[i] < nums[i - 1])
- down = up + 1;
- else if (nums[i] > nums[i - 1])
- up = down + 1;
+ public:
+ int wiggleMaxLength(vector<int> &nums) {
+ if (nums.size() == 0) return 0;
+ int up = 1, down = 1;
+ for (int i = 1; i < nums.size(); i++) {
+ if (nums[i] < nums[i - 1])
+ down = up + 1;
+ else if (nums[i] > nums[i - 1])
+ up = down + 1;
+ }
+ return max(up, down);
}
- return max(up, down);
- }
};
diff --git a/Problems/0377.cpp b/Problems/0377.cpp
@@ -1,13 +1,13 @@
class Solution {
-public:
- int combinationSum4(vector<int> &nums, int target) {
- vector<long long> dp(target + 1, 0);
- dp[0] = 1;
+ public:
+ int combinationSum4(vector<int> &nums, int target) {
+ vector<long long> dp(target + 1, 0);
+ dp[0] = 1;
- for (int i = 1; i <= target; i++)
- for (int num : nums)
- if (i - num >= 0) dp[i] = (dp[i] + dp[i - num]) % INT_MAX;
+ for (int i = 1; i <= target; i++)
+ for (int num : nums)
+ if (i - num >= 0) dp[i] = (dp[i] + dp[i - num]) % INT_MAX;
- return dp.back();
- }
+ return dp.back();
+ }
};
diff --git a/Problems/0382.cpp b/Problems/0382.cpp
@@ -1,16 +1,18 @@
class Solution {
- ListNode *head = nullptr;
- int size = 0;
+ ListNode *head = nullptr;
+ int size = 0;
-public:
- Solution(ListNode *head) : head(head) {
- for (ListNode *p = head; p; p = p->next) size++;
- }
+ public:
+ Solution(ListNode *head) : head(head) {
+ for (ListNode *p = head; p; p = p->next)
+ size++;
+ }
- int getRandom() {
- int elem = rand() % size;
- ListNode *p = head;
- while (elem--) p = p->next;
- return p->val;
- }
+ int getRandom() {
+ int elem = rand() % size;
+ ListNode *p = head;
+ while (elem--)
+ p = p->next;
+ return p->val;
+ }
};
diff --git a/Problems/0383.cpp b/Problems/0383.cpp
@@ -1,13 +1,14 @@
class Solution {
-public:
- bool canConstruct(string ransomNote, string magazine) {
- unordered_map<char, int> us;
+ public:
+ bool canConstruct(string ransomNote, string magazine) {
+ unordered_map<char, int> us;
- for (char c : magazine) us[c]++;
+ for (char c : magazine)
+ us[c]++;
- for (char c : ransomNote)
- if (!us[c]--) return false;
+ for (char c : ransomNote)
+ if (!us[c]--) return false;
- return true;
- }
+ return true;
+ }
};
diff --git a/Problems/0384.cpp b/Problems/0384.cpp
@@ -1,14 +1,14 @@
class Solution {
- const vector<int> og;
- vector<int> shuffing;
+ const vector<int> og;
+ vector<int> shuffing;
-public:
- Solution(const vector<int> &nums) : og(nums), shuffing(nums) {}
+ public:
+ Solution(const vector<int> &nums) : og(nums), shuffing(nums) {}
- vector<int> reset() { return og; }
+ vector<int> reset() { return og; }
- vector<int> shuffle() {
- random_shuffle(shuffing.begin(), shuffing.end());
- return shuffing;
- }
+ vector<int> shuffle() {
+ random_shuffle(shuffing.begin(), shuffing.end());
+ return shuffing;
+ }
};
diff --git a/Problems/0387.cpp b/Problems/0387.cpp
@@ -1,10 +1,11 @@
class Solution {
-public:
- int firstUniqChar(string s) {
- vector<int> um(26, 0);
- for (char c : s) um[c - 'a']++;
- for (int i = 0; i < s.size(); i++)
- if (um[s[i] - 'a'] == 1) return i;
- return -1;
- }
+ public:
+ int firstUniqChar(string s) {
+ vector<int> um(26, 0);
+ for (char c : s)
+ um[c - 'a']++;
+ for (int i = 0; i < s.size(); i++)
+ if (um[s[i] - 'a'] == 1) return i;
+ return -1;
+ }
};
diff --git a/Problems/0392.cpp b/Problems/0392.cpp
@@ -1,9 +1,9 @@
class Solution {
-public:
- bool isSubsequence(string s, string t) {
- int i = 0;
- for (int j = 0; j < t.size() && i < s.size(); j++)
- if (s[i] == t[j]) i++;
- return i == s.size();
- }
+ public:
+ bool isSubsequence(string s, string t) {
+ int i = 0;
+ for (int j = 0; j < t.size() && i < s.size(); j++)
+ if (s[i] == t[j]) i++;
+ return i == s.size();
+ }
};
diff --git a/Problems/0394.cpp b/Problems/0394.cpp
@@ -1,30 +1,31 @@
class Solution {
-public:
- string decodeString(string s) {
- stack<int> is;
- stack<string> ss;
+ public:
+ string decodeString(string s) {
+ stack<int> is;
+ stack<string> ss;
- ss.push("");
- for (int i = 0; i < s.size(); i++) {
- if (isdigit(s[i])) {
- int res = 0;
- do {
- res *= 10;
- res += s[i] - '0';
- } while (isdigit(s[++i]));
- is.push(res);
ss.push("");
- } else if (s[i] == ']') {
- string res = "";
- while (is.top()--) res += ss.top();
- is.pop();
- ss.pop();
- ss.top() += res;
- } else {
- ss.top() += s[i];
- }
- }
+ for (int i = 0; i < s.size(); i++) {
+ if (isdigit(s[i])) {
+ int res = 0;
+ do {
+ res *= 10;
+ res += s[i] - '0';
+ } while (isdigit(s[++i]));
+ is.push(res);
+ ss.push("");
+ } else if (s[i] == ']') {
+ string res = "";
+ while (is.top()--)
+ res += ss.top();
+ is.pop();
+ ss.pop();
+ ss.top() += res;
+ } else {
+ ss.top() += s[i];
+ }
+ }
- return ss.top();
- }
+ return ss.top();
+ }
};
diff --git a/Problems/0399.cpp b/Problems/0399.cpp
@@ -1,47 +1,45 @@
class Solution {
- const int SIZE = 26 * 5;
+ const int SIZE = 26 * 5;
- int hash(const string &st) {
- static int index = 0;
- static unordered_map<string, int> um;
- if (!um.count(st)) um[st] = index++;
- return um[st];
- }
+ int hash(const string &st) {
+ static int index = 0;
+ static unordered_map<string, int> um;
+ if (!um.count(st)) um[st] = index++;
+ return um[st];
+ }
- double dfs(vector<vector<pair<int, double>>> &adj, int start, int goal) {
- stack<pair<int, double>> st;
- vector<bool> visited(SIZE, false);
+ double dfs(vector<vector<pair<int, double>>> &adj, int start, int goal) {
+ stack<pair<int, double>> st;
+ vector<bool> visited(SIZE, false);
- st.push({start, 1});
- visited[start] = true;
- while (!st.empty()) {
- auto [root, value] = st.top();
- st.pop();
- if (root == goal) return value;
- visited[root] = true;
- for (auto &v : adj[root])
- if (!visited[v.first]) st.push({v.first, value * v.second});
+ st.push({start, 1});
+ visited[start] = true;
+ while (!st.empty()) {
+ auto [root, value] = st.top();
+ st.pop();
+ if (root == goal) return value;
+ visited[root] = true;
+ for (auto &v : adj[root])
+ if (!visited[v.first]) st.push({v.first, value * v.second});
+ }
+ return -1;
}
- return -1;
- }
-public:
- vector<double> calcEquation(vector<vector<string>> &equations,
- vector<double> &values,
- vector<vector<string>> &queries) {
- vector<vector<pair<int, double>>> adj(SIZE, vector<pair<int, double>>());
- for (int i = 0; i < values.size(); i++) {
- adj[hash(equations[i][0])].push_back({hash(equations[i][1]), values[i]});
- adj[hash(equations[i][1])].push_back(
- {hash(equations[i][0]), 1 / values[i]});
- }
+ public:
+ vector<double> calcEquation(vector<vector<string>> &equations, vector<double> &values,
+ vector<vector<string>> &queries) {
+ vector<vector<pair<int, double>>> adj(SIZE, vector<pair<int, double>>());
+ for (int i = 0; i < values.size(); i++) {
+ adj[hash(equations[i][0])].push_back({hash(equations[i][1]), values[i]});
+ adj[hash(equations[i][1])].push_back({hash(equations[i][0]), 1 / values[i]});
+ }
- vector<double> res(queries.size(), -1);
- for (int i = 0; i < queries.size(); i++) {
- int start = hash(queries[i][0]), goal = hash(queries[i][1]);
- if (adj[start].empty() || adj[goal].empty()) continue;
- res[i] = dfs(adj, start, goal);
+ vector<double> res(queries.size(), -1);
+ for (int i = 0; i < queries.size(); i++) {
+ int start = hash(queries[i][0]), goal = hash(queries[i][1]);
+ if (adj[start].empty() || adj[goal].empty()) continue;
+ res[i] = dfs(adj, start, goal);
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0402.cpp b/Problems/0402.cpp
@@ -1,28 +1,30 @@
class Solution {
- class Solution {
- public:
- string removeKdigits(string num, int k) {
- if (num.length() <= k) return "0";
- if (k == 0) return num;
+ class Solution {
+ public:
+ string removeKdigits(string num, int k) {
+ if (num.length() <= k) return "0";
+ if (k == 0) return num;
- string res = "";
- stack<char> s;
+ string res = "";
+ stack<char> s;
- s.push(num[0]);
- for (int i = 1; i < num.length(); ++i) {
- while (k > 0 && !s.empty() && num[i] < s.top()) {
- --k;
- s.pop();
- }
- s.push(num[i]);
- if (s.size() == 1 && num[i] == '0') s.pop();
- }
+ s.push(num[0]);
+ for (int i = 1; i < num.length(); ++i) {
+ while (k > 0 && !s.empty() && num[i] < s.top()) {
+ --k;
+ s.pop();
+ }
+ s.push(num[i]);
+ if (s.size() == 1 && num[i] == '0') s.pop();
+ }
- while (k && !s.empty()) --k, s.pop();
+ while (k && !s.empty())
+ --k, s.pop();
- while (!s.empty()) res.push_back(s.top()), s.pop();
+ while (!s.empty())
+ res.push_back(s.top()), s.pop();
- reverse(res.begin(), res.end());
- return res.size() ? res : "0";
- }
- };
+ reverse(res.begin(), res.end());
+ return res.size() ? res : "0";
+ }
+ };
diff --git a/Problems/0404.cpp b/Problems/0404.cpp
@@ -1,23 +1,23 @@
class Solution {
-public:
- int sumOfLeftLeaves(TreeNode *root) {
- if (!root) return 0;
+ public:
+ int sumOfLeftLeaves(TreeNode *root) {
+ if (!root) return 0;
- int res = 0;
- stack<TreeNode *> st;
+ int res = 0;
+ stack<TreeNode *> st;
- st.push(root);
- while (!st.empty()) {
- TreeNode *root = st.top();
- st.pop();
- if (root->left) {
- if (!root->left->left && !root->left->right)
- res += root->left->val;
- else
- st.push(root->left);
- }
- if (root->right) st.push(root->right);
+ st.push(root);
+ while (!st.empty()) {
+ TreeNode *root = st.top();
+ st.pop();
+ if (root->left) {
+ if (!root->left->left && !root->left->right)
+ res += root->left->val;
+ else
+ st.push(root->left);
+ }
+ if (root->right) st.push(root->right);
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0406.cpp b/Problems/0406.cpp
@@ -1,12 +1,12 @@
class Solution {
-public:
- vector<vector<int>> reconstructQueue(vector<vector<int>> &people) {
- sort(begin(people), end(people), [](const auto &a, const auto &b) {
- return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]);
- });
- vector<vector<int>> res;
- res.reserve(people.size());
- for (const auto &p : people) res.insert(res.begin() + p[1], p);
- return res;
- }
+ public:
+ vector<vector<int>> reconstructQueue(vector<vector<int>> &people) {
+ sort(begin(people), end(people),
+ [](const auto &a, const auto &b) { return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]); });
+ vector<vector<int>> res;
+ res.reserve(people.size());
+ for (const auto &p : people)
+ res.insert(res.begin() + p[1], p);
+ return res;
+ }
};
diff --git a/Problems/0409.cpp b/Problems/0409.cpp
@@ -1,15 +1,16 @@
class Solution {
-public:
- int longestPalindrome(string s) {
- unordered_map<char, int> um;
- for (char c : s) um[c]++;
+ public:
+ int longestPalindrome(string s) {
+ unordered_map<char, int> um;
+ for (char c : s)
+ um[c]++;
- int res = 0;
- bool odd = false;
- for (auto [c, v] : um) {
- if (v % 2 && !odd) odd = true;
- res += v / 2;
+ int res = 0;
+ bool odd = false;
+ for (auto [c, v] : um) {
+ if (v % 2 && !odd) odd = true;
+ res += v / 2;
+ }
+ return res * 2 + odd;
}
- return res * 2 + odd;
- }
};
diff --git a/Problems/0412.cpp b/Problems/0412.cpp
@@ -1,19 +1,19 @@
class Solution {
-public:
- vector<string> fizzBuzz(int n) {
- vector<string> res;
+ public:
+ vector<string> fizzBuzz(int n) {
+ vector<string> res;
- for (int i = 1; i <= n; i++) {
- string s = "";
+ for (int i = 1; i <= n; i++) {
+ string s = "";
- if (i % 3 == 0) s += "Fizz";
+ if (i % 3 == 0) s += "Fizz";
- if (i % 5 == 0) s += "Buzz";
+ if (i % 5 == 0) s += "Buzz";
- if (s == "") s = to_string(i);
+ if (s == "") s = to_string(i);
- res.push_back(s);
+ res.push_back(s);
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0413.cpp b/Problems/0413.cpp
@@ -1,16 +1,16 @@
class Solution {
-public:
- int numberOfArithmeticSlices(vector<int> &nums) {
- int total = 0, crnt, cdiff = INT_MIN;
- for (int i = 1; i < nums.size(); i++) {
- int diff = nums[i] - nums[i - 1];
- if (diff != cdiff) {
- crnt = 0;
- cdiff = diff;
- continue;
- }
- total += ++crnt;
+ public:
+ int numberOfArithmeticSlices(vector<int> &nums) {
+ int total = 0, crnt, cdiff = INT_MIN;
+ for (int i = 1; i < nums.size(); i++) {
+ int diff = nums[i] - nums[i - 1];
+ if (diff != cdiff) {
+ crnt = 0;
+ cdiff = diff;
+ continue;
+ }
+ total += ++crnt;
+ }
+ return total;
}
- return total;
- }
};
diff --git a/Problems/0414.cpp b/Problems/0414.cpp
@@ -1,27 +1,29 @@
class Solution {
-public:
- int thirdMax(vector<int> &nums) {
- long long firstMax = numeric_limits<long long>::min();
- long long secondMax = numeric_limits<long long>::min();
- long long thirdMax = numeric_limits<long long>::min();
+ public:
+ int thirdMax(vector<int> &nums) {
+ long long firstMax = numeric_limits<long long>::min();
+ long long secondMax = numeric_limits<long long>::min();
+ long long thirdMax = numeric_limits<long long>::min();
- for (int &num : nums) {
- if (firstMax == num || secondMax == num || thirdMax == num) { continue; }
+ for (int &num : nums) {
+ if (firstMax == num || secondMax == num || thirdMax == num) {
+ continue;
+ }
- if (firstMax <= num) {
- thirdMax = secondMax;
- secondMax = firstMax;
- firstMax = num;
- } else if (secondMax <= num) {
- thirdMax = secondMax;
- secondMax = num;
- } else if (thirdMax <= num) {
- thirdMax = num;
- }
- }
+ if (firstMax <= num) {
+ thirdMax = secondMax;
+ secondMax = firstMax;
+ firstMax = num;
+ } else if (secondMax <= num) {
+ thirdMax = secondMax;
+ secondMax = num;
+ } else if (thirdMax <= num) {
+ thirdMax = num;
+ }
+ }
- if (thirdMax == numeric_limits<long long>::min()) return firstMax;
+ if (thirdMax == numeric_limits<long long>::min()) return firstMax;
- return thirdMax;
- }
+ return thirdMax;
+ }
};
diff --git a/Problems/0415.cpp b/Problems/0415.cpp
@@ -1,21 +1,21 @@
class Solution {
-public:
- string addStrings(string num1, string num2) {
- if (num1 == "0" && num2 == "0") return "0";
+ public:
+ string addStrings(string num1, string num2) {
+ if (num1 == "0" && num2 == "0") return "0";
- string res = "";
- int i = num1.size() - 1;
- int j = num2.size() - 1;
+ string res = "";
+ int i = num1.size() - 1;
+ int j = num2.size() - 1;
- int add = 0;
- while (i >= 0 || j >= 0 || add) {
- if (i >= 0) add += num1[i--] - '0';
- if (j >= 0) add += num2[j--] - '0';
- res += to_string(add % 10);
- add /= 10;
- }
+ int add = 0;
+ while (i >= 0 || j >= 0 || add) {
+ if (i >= 0) add += num1[i--] - '0';
+ if (j >= 0) add += num2[j--] - '0';
+ res += to_string(add % 10);
+ add /= 10;
+ }
- reverse(res.begin(), res.end());
- return res;
- }
+ reverse(res.begin(), res.end());
+ return res;
+ }
};
diff --git a/Problems/0416.cpp b/Problems/0416.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- bool canPartition(vector<int> &nums) {
- int sum = accumulate(nums.begin(), nums.end(), 0), hsum = sum / 2;
- if (sum % 2) return false;
- vector<bool> dp(hsum + 1, false);
+ public:
+ bool canPartition(vector<int> &nums) {
+ int sum = accumulate(nums.begin(), nums.end(), 0), hsum = sum / 2;
+ if (sum % 2) return false;
+ vector<bool> dp(hsum + 1, false);
- dp[0] = true;
- for (int num : nums)
- for (int j = hsum; j >= num; j--)
- if (dp[j - num]) dp[j] = true;
+ dp[0] = true;
+ for (int num : nums)
+ for (int j = hsum; j >= num; j--)
+ if (dp[j - num]) dp[j] = true;
- return dp.back();
- }
+ return dp.back();
+ }
};
diff --git a/Problems/0417.cpp b/Problems/0417.cpp
@@ -1,54 +1,49 @@
class Solution {
- typedef vector<vector<int>> Matrix;
- typedef vector<vector<bool>> Marked;
- typedef queue<pair<int, int>> Queue;
- const vector<pair<int, int>> offsets = {
- { 0, 1},
- { 0, -1},
- { 1, 0},
- {-1, 0}
- };
-
- int n, m;
- int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }
-
- void dfs(Matrix &mat, Marked &mark, int x, int y) {
- if (mark[x][y]) return;
- Queue q;
-
- q.push({x, y}), mark[x][y] = true;
- while (!q.empty()) {
- auto [a, b] = q.front();
- q.pop();
- for (auto [oa, ob] : offsets) {
- int x = a + oa, y = b + ob;
- if (!valid(x, y) || mark[x][y] || mat[x][y] < mat[a][b]) continue;
- mark[x][y] = true;
- q.push({x, y});
- }
+ typedef vector<vector<int>> Matrix;
+ typedef vector<vector<bool>> Marked;
+ typedef queue<pair<int, int>> Queue;
+ const vector<pair<int, int>> offsets = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
+
+ int n, m;
+ int valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }
+
+ void dfs(Matrix &mat, Marked &mark, int x, int y) {
+ if (mark[x][y]) return;
+ Queue q;
+
+ q.push({x, y}), mark[x][y] = true;
+ while (!q.empty()) {
+ auto [a, b] = q.front();
+ q.pop();
+ for (auto [oa, ob] : offsets) {
+ int x = a + oa, y = b + ob;
+ if (!valid(x, y) || mark[x][y] || mat[x][y] < mat[a][b]) continue;
+ mark[x][y] = true;
+ q.push({x, y});
+ }
+ }
}
- }
-public:
- vector<vector<int>> pacificAtlantic(Matrix &heights) {
- n = heights.size(), m = heights[0].size();
- Marked pac(n, vector<bool>(m, false)), atl(n, vector<bool>(m, false));
+ public:
+ vector<vector<int>> pacificAtlantic(Matrix &heights) {
+ n = heights.size(), m = heights[0].size();
+ Marked pac(n, vector<bool>(m, false)), atl(n, vector<bool>(m, false));
- for (int i = 0; i < n; i++) {
- dfs(heights, pac, i, 0);
- dfs(heights, atl, i, m - 1);
- }
+ for (int i = 0; i < n; i++) {
+ dfs(heights, pac, i, 0);
+ dfs(heights, atl, i, m - 1);
+ }
- for (int i = 0; i < m; i++) {
- dfs(heights, pac, 0, i);
- dfs(heights, atl, n - 1, i);
- }
+ for (int i = 0; i < m; i++) {
+ dfs(heights, pac, 0, i);
+ dfs(heights, atl, n - 1, i);
+ }
- vector<vector<int>> res;
- for (int i = 0; i < n; i++)
- for (int j = 0; j < m; j++)
- if (pac[i][j] && atl[i][j]) res.push_back({i, j});
+ vector<vector<int>> res;
+ for (int i = 0; i < n; i++)
+ for (int j = 0; j < m; j++)
+ if (pac[i][j] && atl[i][j]) res.push_back({i, j});
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0419.cpp b/Problems/0419.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- int countBattleships(const vector<vector<char>> &board) {
- int res = 0;
- for (int i = 0; i < board.size(); i++) {
- for (int j = 0; j < board[0].size(); j++) {
- if (board[i][j] == '.') continue;
- if (i > 0 && board[i - 1][j] == 'X') continue;
- if (j > 0 && board[i][j - 1] == 'X') continue;
- res++;
- }
+ public:
+ int countBattleships(const vector<vector<char>> &board) {
+ int res = 0;
+ for (int i = 0; i < board.size(); i++) {
+ for (int j = 0; j < board[0].size(); j++) {
+ if (board[i][j] == '.') continue;
+ if (i > 0 && board[i - 1][j] == 'X') continue;
+ if (j > 0 && board[i][j - 1] == 'X') continue;
+ res++;
+ }
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0424.cpp b/Problems/0424.cpp
@@ -1,18 +1,19 @@
class Solution {
-public:
- int characterReplacement(string s, int k) {
- vector<int> counts(26, 0);
- int n = s.length(), start = 0, maxi = 0, result = 0;
- for_each(s.begin(), s.end(), [](char &c) { c -= 'A'; });
+ public:
+ int characterReplacement(string s, int k) {
+ vector<int> counts(26, 0);
+ int n = s.length(), start = 0, maxi = 0, result = 0;
+ for_each(s.begin(), s.end(), [](char &c) { c -= 'A'; });
- for (int end = 0; end < n; end++) {
- maxi = max(maxi, ++counts[s[end]]);
- while (end - start - maxi + 1 > k) {
- counts[s[start++]]--;
- for (int i = 0; i < 26; i++) maxi = max(maxi, counts[i]);
- }
- result = max(result, end - start + 1);
+ for (int end = 0; end < n; end++) {
+ maxi = max(maxi, ++counts[s[end]]);
+ while (end - start - maxi + 1 > k) {
+ counts[s[start++]]--;
+ for (int i = 0; i < 26; i++)
+ maxi = max(maxi, counts[i]);
+ }
+ result = max(result, end - start + 1);
+ }
+ return result;
}
- return result;
- }
};
diff --git a/Problems/0427.cpp b/Problems/0427.cpp
@@ -1,33 +1,32 @@
class Solution {
-public:
- Node *construct(vector<vector<int>> &grid, int rowStart, int rowEnd,
- int colStart, int colEnd) {
- if (rowStart > rowEnd || colStart > colEnd) return nullptr;
+ public:
+ Node *construct(vector<vector<int>> &grid, int rowStart, int rowEnd, int colStart, int colEnd) {
+ if (rowStart > rowEnd || colStart > colEnd) return nullptr;
- bool isLeaf = true;
- int val = grid[rowStart][colStart];
- for (int i = rowStart; i <= rowEnd; i++) {
- for (int j = colStart; j <= colEnd; j++) {
- if (grid[i][j] != val) {
- isLeaf = false;
- break;
+ bool isLeaf = true;
+ int val = grid[rowStart][colStart];
+ for (int i = rowStart; i <= rowEnd; i++) {
+ for (int j = colStart; j <= colEnd; j++) {
+ if (grid[i][j] != val) {
+ isLeaf = false;
+ break;
+ }
+ }
+ if (!isLeaf) break;
}
- }
- if (!isLeaf) break;
- }
- if (isLeaf) return new Node(val, true);
+ if (isLeaf) return new Node(val, true);
- int rowMid = (rowStart + rowEnd) / 2;
- int colMid = (colStart + colEnd) / 2;
- Node *topLeft = construct(grid, rowStart, rowMid, colStart, colMid);
- Node *topRight = construct(grid, rowStart, rowMid, colMid + 1, colEnd);
- Node *bottomLeft = construct(grid, rowMid + 1, rowEnd, colStart, colMid);
- Node *bottomRight = construct(grid, rowMid + 1, rowEnd, colMid + 1, colEnd);
- return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight);
- }
- Node *construct(vector<vector<int>> &grid) {
- int n = grid.size();
- return construct(grid, 0, n - 1, 0, n - 1);
- }
+ int rowMid = (rowStart + rowEnd) / 2;
+ int colMid = (colStart + colEnd) / 2;
+ Node *topLeft = construct(grid, rowStart, rowMid, colStart, colMid);
+ Node *topRight = construct(grid, rowStart, rowMid, colMid + 1, colEnd);
+ Node *bottomLeft = construct(grid, rowMid + 1, rowEnd, colStart, colMid);
+ Node *bottomRight = construct(grid, rowMid + 1, rowEnd, colMid + 1, colEnd);
+ return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight);
+ }
+ Node *construct(vector<vector<int>> &grid) {
+ int n = grid.size();
+ return construct(grid, 0, n - 1, 0, n - 1);
+ }
};
diff --git a/Problems/0429.cpp b/Problems/0429.cpp
@@ -1,21 +1,22 @@
class Solution {
-public:
- vector<vector<int>> levelOrder(Node *root) {
- if (!root) return {};
+ public:
+ vector<vector<int>> levelOrder(Node *root) {
+ if (!root) return {};
- vector<vector<int>> res;
- queue<Node *> q;
+ vector<vector<int>> res;
+ queue<Node *> q;
- q.push(root);
- for (int lvl = 0; !q.empty(); lvl++) {
- res.push_back(vector<int>());
- for (int t = q.size(); t > 0; t--) {
- Node *root = q.front();
- q.pop();
- res[lvl].push_back(root->val);
- for (Node *c : root->children) q.push(c);
- }
+ q.push(root);
+ for (int lvl = 0; !q.empty(); lvl++) {
+ res.push_back(vector<int>());
+ for (int t = q.size(); t > 0; t--) {
+ Node *root = q.front();
+ q.pop();
+ res[lvl].push_back(root->val);
+ for (Node *c : root->children)
+ q.push(c);
+ }
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0430.cpp b/Problems/0430.cpp
@@ -1,34 +1,34 @@
class Solution {
- void insert_after(Node **t, Node *n) {
- n->prev = *t;
- n->child = nullptr;
- (*t) = (*t)->next = n;
- }
+ void insert_after(Node **t, Node *n) {
+ n->prev = *t;
+ n->child = nullptr;
+ (*t) = (*t)->next = n;
+ }
-public:
- Node *flatten(Node *head) {
- if (!head) return nullptr;
+ public:
+ Node *flatten(Node *head) {
+ if (!head) return nullptr;
- stack<Node *> s;
- s.push(head);
+ stack<Node *> s;
+ s.push(head);
- Node *h, *t;
- t = h = new Node();
- while (!s.empty()) {
- Node *self = s.top();
- s.pop();
- if (self->next) s.push(self->next);
- Node *child = self->child;
- insert_after(&t, self);
- while (child) {
- self = child;
- child = self->child;
- insert_after(&t, self);
- if (self->next) s.push(self->next);
- }
+ Node *h, *t;
+ t = h = new Node();
+ while (!s.empty()) {
+ Node *self = s.top();
+ s.pop();
+ if (self->next) s.push(self->next);
+ Node *child = self->child;
+ insert_after(&t, self);
+ while (child) {
+ self = child;
+ child = self->child;
+ insert_after(&t, self);
+ if (self->next) s.push(self->next);
+ }
+ }
+ t->next = nullptr;
+ h->next->prev = nullptr;
+ return h->next;
}
- t->next = nullptr;
- h->next->prev = nullptr;
- return h->next;
- }
};
diff --git a/Problems/0433.cpp b/Problems/0433.cpp
@@ -1,42 +1,41 @@
class Solution {
- bool mutation(const string &s1, const string &s2) {
- int cnt = 0;
- for (int i = 0; i < size(s1); i++)
- if (s1[i] != s2[i]) cnt++;
- return cnt == 1;
- }
+ bool mutation(const string &s1, const string &s2) {
+ int cnt = 0;
+ for (int i = 0; i < size(s1); i++)
+ if (s1[i] != s2[i]) cnt++;
+ return cnt == 1;
+ }
-public:
- int minMutation(string startGene, string endGene, vector<string> &bank) {
- /* unordered_map<string, vector<string>> um; */
+ public:
+ int minMutation(string startGene, string endGene, vector<string> &bank) {
+ /* unordered_map<string, vector<string>> um; */
- /* if (find(bank.begin(), bank.end(), startGene) == bank.end()) */
- /* bank.push_back(startGene); */
+ /* if (find(bank.begin(), bank.end(), startGene) == bank.end()) */
+ /* bank.push_back(startGene); */
- /* for (int i = 0; i < size(bank); i++) { */
- /* for (int j = i + 1; j < size(bank); j++) */
- /* if (mutation(bank[i], bank[j])) { */
- /* um[bank[i]].push_back(bank[j]); */
- /* um[bank[j]].push_back(bank[i]); */
- /* } */
- /* } */
+ /* for (int i = 0; i < size(bank); i++) { */
+ /* for (int j = i + 1; j < size(bank); j++) */
+ /* if (mutation(bank[i], bank[j])) { */
+ /* um[bank[i]].push_back(bank[j]); */
+ /* um[bank[j]].push_back(bank[i]); */
+ /* } */
+ /* } */
- int mini = INT_MAX;
- unordered_set<string> visited;
- queue<pair<string, int>> st;
- st.push({startGene, 0});
- while (!st.empty()) {
- string root = st.front().first;
- int count = st.front().second;
- st.pop();
- visited.insert(root);
- if (root == endGene) return count;
- /* for (string &s : um[root]) */
- /* if (visited.find(s) == visited.end()) st.push({s, count + 1}); */
- for (string &s : bank)
- if (visited.find(s) == visited.end() && mutation(root, s))
- st.push({s, count + 1});
+ int mini = INT_MAX;
+ unordered_set<string> visited;
+ queue<pair<string, int>> st;
+ st.push({startGene, 0});
+ while (!st.empty()) {
+ string root = st.front().first;
+ int count = st.front().second;
+ st.pop();
+ visited.insert(root);
+ if (root == endGene) return count;
+ /* for (string &s : um[root]) */
+ /* if (visited.find(s) == visited.end()) st.push({s, count + 1}); */
+ for (string &s : bank)
+ if (visited.find(s) == visited.end() && mutation(root, s)) st.push({s, count + 1});
+ }
+ return -1;
}
- return -1;
- }
};
diff --git a/Problems/0435.cpp b/Problems/0435.cpp
@@ -1,20 +1,18 @@
class Solution {
- typedef vector<int> interval;
+ typedef vector<int> interval;
-public:
- int eraseOverlapIntervals(vector<interval> &intervals) {
- auto cmp = [](const interval &i1, const interval &i2) {
- return i1[1] < i2[1];
- };
- sort(intervals.begin(), intervals.end(), cmp);
+ public:
+ int eraseOverlapIntervals(vector<interval> &intervals) {
+ auto cmp = [](const interval &i1, const interval &i2) { return i1[1] < i2[1]; };
+ sort(intervals.begin(), intervals.end(), cmp);
- int end = intervals[0][1], count = 1;
- for (auto &i : intervals) {
- if (i[0] >= end) {
- end = i[1];
- count++;
- }
+ int end = intervals[0][1], count = 1;
+ for (auto &i : intervals) {
+ if (i[0] >= end) {
+ end = i[1];
+ count++;
+ }
+ }
+ return intervals.size() - count;
}
- return intervals.size() - count;
- }
};
diff --git a/Problems/0437.cpp b/Problems/0437.cpp
@@ -1,70 +1,70 @@
// Brute force
class Solution {
-public:
- int pathSum(TreeNode *root, int targetSum) {
- if (!root) return 0;
+ public:
+ int pathSum(TreeNode *root, int targetSum) {
+ if (!root) return 0;
- stack<TreeNode *> st;
- queue<TreeNode *> q;
+ stack<TreeNode *> st;
+ queue<TreeNode *> q;
- st.push(root);
- while (!st.empty()) {
- TreeNode *root = st.top();
- st.pop();
- q.push(root);
- if (root->left) st.push(root->left);
- if (root->right) st.push(root->right);
- }
+ st.push(root);
+ while (!st.empty()) {
+ TreeNode *root = st.top();
+ st.pop();
+ q.push(root);
+ if (root->left) st.push(root->left);
+ if (root->right) st.push(root->right);
+ }
- int res = 0;
- while (!q.empty()) {
- stack<pair<TreeNode *, long long>> st;
- st.push({q.front(), 0});
- q.pop();
- while (!st.empty()) {
- auto [root, sum] = st.top();
- st.pop();
- sum += root->val;
- if (sum == targetSum) res++;
- if (root->left) st.push({root->left, sum});
- if (root->right) st.push({root->right, sum});
- }
- }
+ int res = 0;
+ while (!q.empty()) {
+ stack<pair<TreeNode *, long long>> st;
+ st.push({q.front(), 0});
+ q.pop();
+ while (!st.empty()) {
+ auto [root, sum] = st.top();
+ st.pop();
+ sum += root->val;
+ if (sum == targetSum) res++;
+ if (root->left) st.push({root->left, sum});
+ if (root->right) st.push({root->right, sum});
+ }
+ }
- return res;
- }
+ return res;
+ }
};
// Optimized
class Solution {
-public:
- int pathSum(TreeNode *root, int targetSum) {
- if (!root) return 0;
- queue<pair<TreeNode *, vector<long long>>> q;
- int res = 0;
+ public:
+ int pathSum(TreeNode *root, int targetSum) {
+ if (!root) return 0;
+ queue<pair<TreeNode *, vector<long long>>> q;
+ int res = 0;
- q.push({root, {}});
- while (!q.empty()) {
- auto &[root, vec] = q.front();
- long long sum = root->val + (vec.size() ? vec.back() : 0);
+ q.push({root, {}});
+ while (!q.empty()) {
+ auto &[root, vec] = q.front();
+ long long sum = root->val + (vec.size() ? vec.back() : 0);
- for (int num : vec)
- if (sum - num == targetSum) res++;
- if (sum == targetSum) res++;
+ for (int num : vec)
+ if (sum - num == targetSum) res++;
+ if (sum == targetSum) res++;
- if (root->left) {
- q.push({root->left, vec});
- q.back().second.push_back(sum);
- }
+ if (root->left) {
+ q.push({root->left, vec});
+ q.back().second.push_back(sum);
+ }
- if (root->right) {
- q.push({root->right, vec});
- q.back().second.push_back(sum);
- }
+ if (root->right) {
+ q.push({root->right, vec});
+ q.back().second.push_back(sum);
+ }
- q.pop();
- }
+ q.pop();
+ }
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0438.cpp b/Problems/0438.cpp
@@ -1,31 +1,31 @@
class Solution {
- typedef unordered_map<char, int> umci;
- bool um_eq(const umci &goal, const umci &crnt) {
- for (auto [k, v] : goal) {
- const auto it = crnt.find(k);
- if (it == crnt.end()) return false;
- if ((*it).second != v) return false;
+ typedef unordered_map<char, int> umci;
+ bool um_eq(const umci &goal, const umci &crnt) {
+ for (auto [k, v] : goal) {
+ const auto it = crnt.find(k);
+ if (it == crnt.end()) return false;
+ if ((*it).second != v) return false;
+ }
+ return true;
}
- return true;
- }
-public:
- vector<int> findAnagrams(string s, string p) {
- if (p.size() > s.size()) return {};
- unordered_map<char, int> goal, crnt;
+ public:
+ vector<int> findAnagrams(string s, string p) {
+ if (p.size() > s.size()) return {};
+ unordered_map<char, int> goal, crnt;
- for (int i = 0; i < p.size(); i++) {
- goal[p[i]]++;
- crnt[s[i]]++;
- }
+ for (int i = 0; i < p.size(); i++) {
+ goal[p[i]]++;
+ crnt[s[i]]++;
+ }
- vector<int> res;
- for (int i = p.size(); i < s.size(); i++) {
- if (um_eq(goal, crnt)) res.push_back(i - p.size());
- crnt[s[i - p.size()]]--;
- crnt[s[i]]++;
+ vector<int> res;
+ for (int i = p.size(); i < s.size(); i++) {
+ if (um_eq(goal, crnt)) res.push_back(i - p.size());
+ crnt[s[i - p.size()]]--;
+ crnt[s[i]]++;
+ }
+ if (um_eq(goal, crnt)) res.push_back(s.size() - p.size());
+ return res;
}
- if (um_eq(goal, crnt)) res.push_back(s.size() - p.size());
- return res;
- }
};
diff --git a/Problems/0442.cpp b/Problems/0442.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- vector<int> findDuplicates(vector<int> &nums) {
- vector<int> res;
- for (int i = 0; i < nums.size(); i++) {
- int idx = abs(nums[i]) - 1;
- if (nums[idx] < 0)
- res.push_back(idx + 1);
- else
- nums[idx] = -nums[idx];
- }
+ public:
+ vector<int> findDuplicates(vector<int> &nums) {
+ vector<int> res;
+ for (int i = 0; i < nums.size(); i++) {
+ int idx = abs(nums[i]) - 1;
+ if (nums[idx] < 0)
+ res.push_back(idx + 1);
+ else
+ nums[idx] = -nums[idx];
+ }
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0443.cpp b/Problems/0443.cpp
@@ -1,23 +1,25 @@
class Solution {
-public:
- int compress(vector<char> &chars) {
- char prev = chars[0];
- int count = 1, crnt = 0;
- for (int i = 1; i < chars.size(); i++) {
- if (chars[i] == prev)
- count++;
- else {
+ public:
+ int compress(vector<char> &chars) {
+ char prev = chars[0];
+ int count = 1, crnt = 0;
+ for (int i = 1; i < chars.size(); i++) {
+ if (chars[i] == prev)
+ count++;
+ else {
+ chars[crnt++] = prev;
+ if (count != 1)
+ for (char c : to_string(count))
+ chars[crnt++] = c;
+ count = 1;
+ prev = chars[i];
+ }
+ }
chars[crnt++] = prev;
if (count != 1)
- for (char c : to_string(count)) chars[crnt++] = c;
- count = 1;
- prev = chars[i];
- }
- }
- chars[crnt++] = prev;
- if (count != 1)
- for (char c : to_string(count)) chars[crnt++] = c;
+ for (char c : to_string(count))
+ chars[crnt++] = c;
- return crnt;
- }
+ return crnt;
+ }
};
diff --git a/Problems/0445.cpp b/Problems/0445.cpp
@@ -1,9 +1,9 @@
class Solution {
-public:
- pair<ListNode*, int> reverse(ListNode *root) {
+ public:
+ pair<ListNode *, int> reverse(ListNode *root) {
ListNode *l = nullptr, *c = root;
int size = 0;
- while(c) {
+ while (c) {
ListNode *n = c->next;
c->next = l;
l = c;
@@ -13,31 +13,31 @@ public:
return {l, size};
}
- ListNode* addTwoNumbers(ListNode* p1, ListNode* p2) {
+ ListNode *addTwoNumbers(ListNode *p1, ListNode *p2) {
auto [l1, s1] = reverse(p1);
auto [l2, s2] = reverse(p2);
- if(s2 > s1) swap(l1, l2);
+ if (s2 > s1) swap(l1, l2);
p1 = l1;
int carry = 0;
- for(; l1 && l2; l1=l1->next, l2=l2->next) {
+ for (; l1 && l2; l1 = l1->next, l2 = l2->next) {
int sum = l1->val + l2->val + carry;
l1->val = sum % 10;
carry = sum / 10;
}
- if(l1) {
- while(true) {
+ if (l1) {
+ while (true) {
int sum = l1->val + carry;
l1->val = sum % 10;
carry = sum / 10;
- if(!l1->next) break;
+ if (!l1->next) break;
l1 = l1->next;
}
}
- if(!carry) return reverse(p1).first;
+ if (!carry) return reverse(p1).first;
return new ListNode(carry, reverse(p1).first);
}
};
diff --git a/Problems/0448.cpp b/Problems/0448.cpp
@@ -1,16 +1,16 @@
class Solution {
-public:
- vector<int> findDisappearedNumbers(vector<int> &nums) {
- vector<int> res;
+ public:
+ vector<int> findDisappearedNumbers(vector<int> &nums) {
+ vector<int> res;
- for (int i = 0; i < nums.size(); i++) {
- int index = abs(nums[i]) - 1;
- if (nums[index] > 0) nums[index] = -nums[index];
- }
+ for (int i = 0; i < nums.size(); i++) {
+ int index = abs(nums[i]) - 1;
+ if (nums[index] > 0) nums[index] = -nums[index];
+ }
- for (int i = 0; i < nums.size(); i++)
- if (nums[i] > 0) res.push_back(i + 1);
+ for (int i = 0; i < nums.size(); i++)
+ if (nums[i] > 0) res.push_back(i + 1);
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0450.cpp b/Problems/0450.cpp
@@ -1,33 +1,33 @@
class Solution {
- TreeNode *deleteRoot(TreeNode *root) {
- if (!root) return nullptr;
- if (!root->left) return root->right;
- if (!root->right) return root->left;
+ TreeNode *deleteRoot(TreeNode *root) {
+ if (!root) return nullptr;
+ if (!root->left) return root->right;
+ if (!root->right) return root->left;
- TreeNode *next = root->right;
- TreeNode *pre = nullptr;
- while (next->left) {
- pre = next;
- next = next->left;
+ TreeNode *next = root->right;
+ TreeNode *pre = nullptr;
+ while (next->left) {
+ pre = next;
+ next = next->left;
+ }
+ next->left = root->left;
+ if (root->right != next) {
+ pre->left = next->right;
+ next->right = root->right;
+ }
+ return next;
}
- next->left = root->left;
- if (root->right != next) {
- pre->left = next->right;
- next->right = root->right;
- }
- return next;
- }
-public:
- TreeNode *deleteNode(TreeNode *root, int key) {
- TreeNode *cur = root, *pre = nullptr;
- while (cur && cur->val != key) {
- pre = cur;
- cur = key < cur->val ? cur->left : cur->right;
- }
+ public:
+ TreeNode *deleteNode(TreeNode *root, int key) {
+ TreeNode *cur = root, *pre = nullptr;
+ while (cur && cur->val != key) {
+ pre = cur;
+ cur = key < cur->val ? cur->left : cur->right;
+ }
- if (!pre) return deleteRoot(cur);
- (pre->left == cur ? pre->left : pre->right) = deleteRoot(cur);
- return root;
- }
+ if (!pre) return deleteRoot(cur);
+ (pre->left == cur ? pre->left : pre->right) = deleteRoot(cur);
+ return root;
+ }
};
diff --git a/Problems/0451.cpp b/Problems/0451.cpp
@@ -1,11 +1,11 @@
class Solution {
-public:
- string frequencySort(string s) {
- array<int, 128> um = {0};
- for (char c : s) um[c]++;
- sort(s.begin(), s.end(), [&um](char a, char b) {
- return um[a] > um[b] || (um[a] == um[b] && a < b);
- });
- return s;
- }
+ public:
+ string frequencySort(string s) {
+ array<int, 128> um = {0};
+ for (char c : s)
+ um[c]++;
+ sort(s.begin(), s.end(),
+ [&um](char a, char b) { return um[a] > um[b] || (um[a] == um[b] && a < b); });
+ return s;
+ }
};
diff --git a/Problems/0452.cpp b/Problems/0452.cpp
@@ -1,17 +1,17 @@
class Solution {
- typedef vector<int> segment;
+ typedef vector<int> segment;
-public:
- int findMinArrowShots(vector<segment> &segments) {
- auto cmp = [](const segment &a, const segment &b) { return a[1] < b[1]; };
- sort(segments.begin(), segments.end(), cmp);
- int res = 1, arrow = segments[0][1];
- for (segment &s : segments) {
- if (s[0] > arrow) {
- res++;
- arrow = s[1];
- }
+ public:
+ int findMinArrowShots(vector<segment> &segments) {
+ auto cmp = [](const segment &a, const segment &b) { return a[1] < b[1]; };
+ sort(segments.begin(), segments.end(), cmp);
+ int res = 1, arrow = segments[0][1];
+ for (segment &s : segments) {
+ if (s[0] > arrow) {
+ res++;
+ arrow = s[1];
+ }
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0459.cpp b/Problems/0459.cpp
@@ -1,14 +1,15 @@
class Solution {
-public:
- bool repeatedSubstringPattern(const string &s) {
- string made;
- for (int i = 1; i <= s.size() / 2; i++) {
- if (s.size() % i) continue;
- const string pref = s.substr(0, i);
- for (int j = 0; j < s.size() / i; j++) made += pref;
- if (made == s) return true;
- made.clear();
+ public:
+ bool repeatedSubstringPattern(const string &s) {
+ string made;
+ for (int i = 1; i <= s.size() / 2; i++) {
+ if (s.size() % i) continue;
+ const string pref = s.substr(0, i);
+ for (int j = 0; j < s.size() / i; j++)
+ made += pref;
+ if (made == s) return true;
+ made.clear();
+ }
+ return false;
}
- return false;
- }
};
diff --git a/Problems/0460.cpp b/Problems/0460.cpp
@@ -1 +1 @@
-Formating: Problems/0460.cpp
+Formating : Problems / 0460.cpp
diff --git a/Problems/0472.cpp b/Problems/0472.cpp
@@ -1 +1 @@
-Formating: Problems/0472.cpp
+Formating : Problems / 0472.cpp
diff --git a/Problems/0485.cpp b/Problems/0485.cpp
@@ -1,15 +1,15 @@
class Solution {
-public:
- int findMaxConsecutiveOnes(vector<int> &nums) {
- int maxi = 0;
- int cnt = 0;
+ public:
+ int findMaxConsecutiveOnes(vector<int> &nums) {
+ int maxi = 0;
+ int cnt = 0;
- for (int i : nums)
- if (i)
- maxi = max(maxi, ++cnt);
- else
- cnt = 0;
+ for (int i : nums)
+ if (i)
+ maxi = max(maxi, ++cnt);
+ else
+ cnt = 0;
- return maxi;
- }
+ return maxi;
+ }
};
diff --git a/Problems/0486.cpp b/Problems/0486.cpp
@@ -1,20 +1,18 @@
class Solution {
- int dp[21][21];
+ int dp[21][21];
- int rec(const vector<int> &nums, int i, int j) {
- if (i == j) return nums[i];
- if (dp[i][j] != -1) return dp[i][j];
+ int rec(const vector<int> &nums, int i, int j) {
+ if (i == j) return nums[i];
+ if (dp[i][j] != -1) return dp[i][j];
- int left = nums[i] - rec(nums, i + 1, j);
- int right = nums[j] - rec(nums, i, j - 1);
+ int left = nums[i] - rec(nums, i + 1, j);
+ int right = nums[j] - rec(nums, i, j - 1);
- return dp[i][j] = max(left, right);
- }
+ return dp[i][j] = max(left, right);
+ }
-public:
- Solution() { memset(dp, 0xFF, sizeof(dp)); }
+ public:
+ Solution() { memset(dp, 0xFF, sizeof(dp)); }
- bool PredictTheWinner(const vector<int> &nums) {
- return rec(nums, 0, nums.size() - 1) >= 0;
- }
+ bool PredictTheWinner(const vector<int> &nums) { return rec(nums, 0, nums.size() - 1) >= 0; }
};
diff --git a/Problems/0491.cpp b/Problems/0491.cpp
@@ -1,23 +1,23 @@
class Solution {
- vector<vector<int>> res;
- vector<int> seq;
+ vector<vector<int>> res;
+ vector<int> seq;
-public:
- vector<vector<int>> findSubsequences(vector<int> &nums) {
- dfs(nums, 0);
- return res;
- }
+ public:
+ vector<vector<int>> findSubsequences(vector<int> &nums) {
+ dfs(nums, 0);
+ return res;
+ }
- void dfs(vector<int> &nums, int pos) {
- if (seq.size() > 1) res.push_back(seq);
- unordered_set<int> hash;
- for (int i = pos; i < nums.size(); i++) {
- if ((seq.empty() || nums[i] >= seq.back()) && !hash.count(nums[i])) {
- seq.push_back(nums[i]);
- dfs(nums, i + 1);
- seq.pop_back();
- hash.insert(nums[i]);
- }
+ void dfs(vector<int> &nums, int pos) {
+ if (seq.size() > 1) res.push_back(seq);
+ unordered_set<int> hash;
+ for (int i = pos; i < nums.size(); i++) {
+ if ((seq.empty() || nums[i] >= seq.back()) && !hash.count(nums[i])) {
+ seq.push_back(nums[i]);
+ dfs(nums, i + 1);
+ seq.pop_back();
+ hash.insert(nums[i]);
+ }
+ }
}
- }
};
diff --git a/Problems/0494.cpp b/Problems/0494.cpp
@@ -1,37 +1,37 @@
// Initial solution
class Solution {
-public:
- int findTargetSumWays(vector<int> &nums, int target) {
- unordered_map<int, int> crnt;
- crnt[0] = 1;
- for (int i = 0; i < nums.size(); i++) {
- unordered_map<int, int> next;
- for (auto &p : crnt) {
- next[p.first + nums[i]] += p.second;
- next[p.first - nums[i]] += p.second;
- }
- crnt = next;
+ public:
+ int findTargetSumWays(vector<int> &nums, int target) {
+ unordered_map<int, int> crnt;
+ crnt[0] = 1;
+ for (int i = 0; i < nums.size(); i++) {
+ unordered_map<int, int> next;
+ for (auto &p : crnt) {
+ next[p.first + nums[i]] += p.second;
+ next[p.first - nums[i]] += p.second;
+ }
+ crnt = next;
+ }
+ return crnt[target];
}
- return crnt[target];
- }
};
// Optimized using array;
class Solution {
-public:
- int findTargetSumWays(vector<int> &nums, int target) {
- int total = accumulate(nums.begin(), nums.end(), 0);
- vector<int> dp(2 * total + 1);
- dp[total] = 1;
- for (int i = 0; i < nums.size(); i++) {
- vector<int> next(2 * total + 1);
- for (int j = 0; j < dp.size(); j++) {
- if (!dp[j]) continue;
- next[j + nums[i]] += dp[j];
- next[j - nums[i]] += dp[j];
- }
- dp = next;
+ public:
+ int findTargetSumWays(vector<int> &nums, int target) {
+ int total = accumulate(nums.begin(), nums.end(), 0);
+ vector<int> dp(2 * total + 1);
+ dp[total] = 1;
+ for (int i = 0; i < nums.size(); i++) {
+ vector<int> next(2 * total + 1);
+ for (int j = 0; j < dp.size(); j++) {
+ if (!dp[j]) continue;
+ next[j + nums[i]] += dp[j];
+ next[j - nums[i]] += dp[j];
+ }
+ dp = next;
+ }
+ return abs(target) > total ? 0 : dp[target + total];
}
- return abs(target) > total ? 0 : dp[target + total];
- }
};
diff --git a/Problems/0496.cpp b/Problems/0496.cpp
@@ -1,21 +1,21 @@
class Solution {
-public:
- vector<int> nextGreaterElement(vector<int> &nums1, vector<int> &nums2) {
- vector<int> res(nums1.size(), -1);
- unordered_map<int, int> um;
- stack<int> st;
+ public:
+ vector<int> nextGreaterElement(vector<int> &nums1, vector<int> &nums2) {
+ vector<int> res(nums1.size(), -1);
+ unordered_map<int, int> um;
+ stack<int> st;
- for (int i = 0; i < nums2.size(); i++) {
- while (!st.empty() && nums2[i] > st.top()) {
- um.insert(make_pair(st.top(), nums2[i]));
- st.pop();
- }
- st.push(nums2[i]);
- }
+ for (int i = 0; i < nums2.size(); i++) {
+ while (!st.empty() && nums2[i] > st.top()) {
+ um.insert(make_pair(st.top(), nums2[i]));
+ st.pop();
+ }
+ st.push(nums2[i]);
+ }
- for (int i = 0; i < nums1.size(); i++)
- if (um.find(nums1[i]) != um.end()) res[i] = um[nums1[i]];
+ for (int i = 0; i < nums1.size(); i++)
+ if (um.find(nums1[i]) != um.end()) res[i] = um[nums1[i]];
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0498.cpp b/Problems/0498.cpp
@@ -1,45 +1,44 @@
class Solution {
-public:
- bool valid(int i, int m, int j, int n) {
- return i >= 0 && i <= m && j >= 0 && j <= n;
- }
+ public:
+ bool valid(int i, int m, int j, int n) { return i >= 0 && i <= m && j >= 0 && j <= n; }
- void quick_adjust(int &i, int &j, bool &up) {
- if (up)
- i++;
- else
- j++;
- up = !up;
- }
+ void quick_adjust(int &i, int &j, bool &up) {
+ if (up)
+ i++;
+ else
+ j++;
+ up = !up;
+ }
- void move(int &i, int &j, bool &up) {
- if (up) {
- i--;
- j++;
- } else {
- i++;
- j--;
+ void move(int &i, int &j, bool &up) {
+ if (up) {
+ i--;
+ j++;
+ } else {
+ i++;
+ j--;
+ }
}
- }
- vector<int> findDiagonalOrder(vector<vector<int>> &mat) {
- vector<int> res;
- bool up = true;
- int i = 0, j = 0;
- int m = mat.size() - 1, n = mat[0].size() - 1;
+ vector<int> findDiagonalOrder(vector<vector<int>> &mat) {
+ vector<int> res;
+ bool up = true;
+ int i = 0, j = 0;
+ int m = mat.size() - 1, n = mat[0].size() - 1;
- while (true) {
- res.push_back(mat[i][j]);
- if (i == m && j == n) break;
+ while (true) {
+ res.push_back(mat[i][j]);
+ if (i == m && j == n) break;
- move(i, j, up);
+ move(i, j, up);
- if (!valid(i, m, j, n)) {
- quick_adjust(i, j, up);
- while (!valid(i, m, j, n)) move(i, j, up);
- }
- }
+ if (!valid(i, m, j, n)) {
+ quick_adjust(i, j, up);
+ while (!valid(i, m, j, n))
+ move(i, j, up);
+ }
+ }
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0501.cpp b/Problems/0501.cpp
@@ -1,34 +1,34 @@
class Solution {
-public:
- vector<int> findMode(TreeNode *root) {
- stack<TreeNode *> st;
+ public:
+ vector<int> findMode(TreeNode *root) {
+ stack<TreeNode *> st;
- int maxi = INT_MIN, cnt = 0, prev = -1;
- vector<int> res;
- while (true) {
- while (root) {
- st.push(root);
- root = root->left;
- }
- if (st.empty()) break;
- root = st.top(), st.pop();
- if (root->val != prev) {
+ int maxi = INT_MIN, cnt = 0, prev = -1;
+ vector<int> res;
+ while (true) {
+ while (root) {
+ st.push(root);
+ root = root->left;
+ }
+ if (st.empty()) break;
+ root = st.top(), st.pop();
+ if (root->val != prev) {
+ if (cnt >= maxi) {
+ if (cnt > maxi) res.clear();
+ maxi = cnt;
+ res.push_back(prev);
+ }
+ prev = root->val;
+ cnt = 1;
+ } else
+ cnt++;
+ root = root->right;
+ }
if (cnt >= maxi) {
- if (cnt > maxi) res.clear();
- maxi = cnt;
- res.push_back(prev);
+ if (cnt > maxi) res.clear();
+ maxi = cnt;
+ res.push_back(prev);
}
- prev = root->val;
- cnt = 1;
- } else
- cnt++;
- root = root->right;
- }
- if (cnt >= maxi) {
- if (cnt > maxi) res.clear();
- maxi = cnt;
- res.push_back(prev);
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0502.cpp b/Problems/0502.cpp
@@ -1,35 +1,35 @@
class Solution {
- typedef pair<int, int> pii;
+ typedef pair<int, int> pii;
-public:
- int findMaximizedCapital(int k, int w, vector<int> &profits,
- vector<int> &capital) {
- vector<pii> data(profits.size());
- for (int i = 0; i < profits.size(); i++) data[i] = {capital[i], profits[i]};
- sort(data.begin(), data.end());
+ public:
+ int findMaximizedCapital(int k, int w, vector<int> &profits, vector<int> &capital) {
+ vector<pii> data(profits.size());
+ for (int i = 0; i < profits.size(); i++)
+ data[i] = {capital[i], profits[i]};
+ sort(data.begin(), data.end());
- auto cmp = [](const pii &a, const pii &b) { return a.second < b.second; };
- priority_queue<pii, vector<pii>, decltype(cmp)> pq(cmp);
+ auto cmp = [](const pii &a, const pii &b) { return a.second < b.second; };
+ priority_queue<pii, vector<pii>, decltype(cmp)> pq(cmp);
- int i = 0;
- while (i < profits.size() && k) {
- if (data[i].first <= w)
- pq.push(data[i++]);
- else {
- while (!pq.empty() && data[i].first > w && k) {
- w += pq.top().second;
- pq.pop();
- k--;
+ int i = 0;
+ while (i < profits.size() && k) {
+ if (data[i].first <= w)
+ pq.push(data[i++]);
+ else {
+ while (!pq.empty() && data[i].first > w && k) {
+ w += pq.top().second;
+ pq.pop();
+ k--;
+ }
+ if (pq.empty() && data[i].first > w) break;
+ }
+ }
+ while (!pq.empty() && k) {
+ w += pq.top().second;
+ pq.pop();
+ k--;
}
- if (pq.empty() && data[i].first > w) break;
- }
- }
- while (!pq.empty() && k) {
- w += pq.top().second;
- pq.pop();
- k--;
- }
- return w;
- }
+ return w;
+ }
};
diff --git a/Problems/0503.cpp b/Problems/0503.cpp
@@ -1,24 +1,24 @@
class Solution {
-public:
- vector<int> nextGreaterElements(vector<int> &nums) {
- vector<int> res(nums.size(), -1);
- stack<int> st;
+ public:
+ vector<int> nextGreaterElements(vector<int> &nums) {
+ vector<int> res(nums.size(), -1);
+ stack<int> st;
- for (int i = 0; i < nums.size(); i++) {
- while (!st.empty() && nums[i] > nums[st.top()]) {
- res[st.top()] = nums[i];
- st.pop();
- }
- st.push(i);
- }
+ for (int i = 0; i < nums.size(); i++) {
+ while (!st.empty() && nums[i] > nums[st.top()]) {
+ res[st.top()] = nums[i];
+ st.pop();
+ }
+ st.push(i);
+ }
- for (int i = 0; !st.empty() && i < nums.size(); i++) {
- while (!st.empty() && nums[i] > nums[st.top()]) {
- res[st.top()] = nums[i];
- st.pop();
- }
- }
+ for (int i = 0; !st.empty() && i < nums.size(); i++) {
+ while (!st.empty() && nums[i] > nums[st.top()]) {
+ res[st.top()] = nums[i];
+ st.pop();
+ }
+ }
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0509.cpp b/Problems/0509.cpp
@@ -1,26 +1,27 @@
// memorization approach
class Solution {
-public:
- int fib(int n) {
- vector<int> f(31);
- f[0] = 0;
- f[1] = 1;
- for (int i = 2; i <= n; i++) f[i] = f[i - 1] + f[i - 2];
- return f[n];
- }
+ public:
+ int fib(int n) {
+ vector<int> f(31);
+ f[0] = 0;
+ f[1] = 1;
+ for (int i = 2; i <= n; i++)
+ f[i] = f[i - 1] + f[i - 2];
+ return f[n];
+ }
};
// optimized, memorize only the previous two values
class Solution {
-public:
- int fib(int n) {
- if (n == 0) return 0;
- int a = 0, b = 1;
- for (int i = 2; i <= n; i++) {
- int tmp = a + b;
- a = b;
- b = tmp;
+ public:
+ int fib(int n) {
+ if (n == 0) return 0;
+ int a = 0, b = 1;
+ for (int i = 2; i <= n; i++) {
+ int tmp = a + b;
+ a = b;
+ b = tmp;
+ }
+ return b;
}
- return b;
- }
};
diff --git a/Problems/0516.cpp b/Problems/0516.cpp
@@ -1,26 +1,25 @@
class Solution {
- int len(const string &s, const int sa, const int sb,
- vector<vector<int>> &mem) {
- if (mem[sa][sb]) return mem[sa][sb];
+ int len(const string &s, const int sa, const int sb, vector<vector<int>> &mem) {
+ if (mem[sa][sb]) return mem[sa][sb];
- int res = 0, a = sa, b = sb;
- while (a < b) {
- if (s[a] == s[b])
- a++, b--, res += 2;
- else {
- res += max(len(s, a + 1, b, mem), len(s, a, b - 1, mem));
- break;
- }
+ int res = 0, a = sa, b = sb;
+ while (a < b) {
+ if (s[a] == s[b])
+ a++, b--, res += 2;
+ else {
+ res += max(len(s, a + 1, b, mem), len(s, a, b - 1, mem));
+ break;
+ }
+ }
+ if (a == b) res++;
+ mem[sa][sb] = res;
+ return res;
}
- if (a == b) res++;
- mem[sa][sb] = res;
- return res;
- }
-public:
- int longestPalindromeSubseq(string s) {
- int n = s.size();
- vector<vector<int>> mem(n, vector<int>(n));
- return len(s, 0, n - 1, mem);
- }
+ public:
+ int longestPalindromeSubseq(string s) {
+ int n = s.size();
+ vector<vector<int>> mem(n, vector<int>(n));
+ return len(s, 0, n - 1, mem);
+ }
};
diff --git a/Problems/0518.cpp b/Problems/0518.cpp
@@ -1,13 +1,13 @@
class Solution {
-public:
- int change(int amount, vector<int> &coins) {
- vector<long long> dp(amount + 1, 0);
- dp[0] = 1;
+ public:
+ int change(int amount, vector<int> &coins) {
+ vector<long long> dp(amount + 1, 0);
+ dp[0] = 1;
- for (int coin : coins)
- for (int i = 0; i <= amount; i++)
- if (i - coin >= 0) dp[i] += dp[i - coin];
+ for (int coin : coins)
+ for (int i = 0; i <= amount; i++)
+ if (i - coin >= 0) dp[i] += dp[i - coin];
- return (int)dp.back();
- }
+ return (int)dp.back();
+ }
};
diff --git a/Problems/0520.cpp b/Problems/0520.cpp
@@ -1,9 +1,9 @@
class Solution {
-public:
- bool detectCapitalUse(string word) {
- int count = 0;
- for (char &c : word) count += c == toupper(c);
- return count == 0 || count == word.size() ||
- (count == 1 && word[0] == toupper(word[0]));
- }
+ public:
+ bool detectCapitalUse(string word) {
+ int count = 0;
+ for (char &c : word)
+ count += c == toupper(c);
+ return count == 0 || count == word.size() || (count == 1 && word[0] == toupper(word[0]));
+ }
};
diff --git a/Problems/0530.cpp b/Problems/0530.cpp
@@ -1,21 +1,21 @@
class Solution {
-public:
- int getMinimumDifference(TreeNode *root) {
- stack<TreeNode *> st;
- int res = INT_MAX;
- TreeNode *prev = new TreeNode(INT_MAX);
- while (true) {
- while (root) {
- st.push(root);
- root = root->left;
- }
- if (st.empty()) break;
- root = st.top();
- st.pop();
- res = min(res, abs(prev->val - root->val));
- prev = root;
- root = root->right;
+ public:
+ int getMinimumDifference(TreeNode *root) {
+ stack<TreeNode *> st;
+ int res = INT_MAX;
+ TreeNode *prev = new TreeNode(INT_MAX);
+ while (true) {
+ while (root) {
+ st.push(root);
+ root = root->left;
+ }
+ if (st.empty()) break;
+ root = st.top();
+ st.pop();
+ res = min(res, abs(prev->val - root->val));
+ prev = root;
+ root = root->right;
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0532.cpp b/Problems/0532.cpp
@@ -1,16 +1,19 @@
class Solution {
-public:
- int findPairs(vector<int> &nums, int k) {
- int res = 0;
- if (k == 0) {
- unordered_map<int, int> um;
- for (int n : nums) um[n]++;
- for (const auto &[n, v] : um) res += v >= 2;
- return res;
- } else {
- unordered_set<int> us(nums.begin(), nums.end());
- for (const auto &n : us) res += us.count(n + k) + us.count(n - k);
- return res / 2;
+ public:
+ int findPairs(vector<int> &nums, int k) {
+ int res = 0;
+ if (k == 0) {
+ unordered_map<int, int> um;
+ for (int n : nums)
+ um[n]++;
+ for (const auto &[n, v] : um)
+ res += v >= 2;
+ return res;
+ } else {
+ unordered_set<int> us(nums.begin(), nums.end());
+ for (const auto &n : us)
+ res += us.count(n + k) + us.count(n - k);
+ return res / 2;
+ }
}
- }
};
diff --git a/Problems/0535.cpp b/Problems/0535.cpp
@@ -1,17 +1,15 @@
class Solution {
unordered_map<string, int> um;
vector<string> str;
-public:
- string encode(const string& longUrl) {
- if(um.count(longUrl)) return to_string(um[longUrl]);
+
+ public:
+ string encode(const string &longUrl) {
+ if (um.count(longUrl)) return to_string(um[longUrl]);
um.insert({longUrl, str.size()});
str.push_back(longUrl);
return to_string(str.size() - 1);
}
- string decode(const string& shortUrl) {
- return str[stoi(shortUrl)];
- }
+ string decode(const string &shortUrl) { return str[stoi(shortUrl)]; }
};
-
diff --git a/Problems/0538.cpp b/Problems/0538.cpp
@@ -1,19 +1,19 @@
class Solution {
-public:
- TreeNode *convertBST(TreeNode *root) {
- TreeNode *head = root;
- stack<TreeNode *> st;
- int sum = 0;
- while (true) {
- while (root) {
- st.push(root);
- root = root->right;
- }
- if (st.empty()) break;
- root = st.top(), st.pop();
- sum = root->val += sum;
- root = root->left;
+ public:
+ TreeNode *convertBST(TreeNode *root) {
+ TreeNode *head = root;
+ stack<TreeNode *> st;
+ int sum = 0;
+ while (true) {
+ while (root) {
+ st.push(root);
+ root = root->right;
+ }
+ if (st.empty()) break;
+ root = st.top(), st.pop();
+ sum = root->val += sum;
+ root = root->left;
+ }
+ return head;
}
- return head;
- }
};
diff --git a/Problems/0540.cpp b/Problems/0540.cpp
@@ -1,15 +1,14 @@
class Solution {
-public:
- int singleNonDuplicate(vector<int> &nums) {
- int low = 0, high = nums.size() - 1;
- while (low < high) {
- int mid = low + (high - low) / 2;
- if ((mid % 2 == 0 && nums[mid] == nums[mid + 1]) ||
- (mid % 2 == 1 && nums[mid] == nums[mid - 1]))
- low = mid + 1;
- else
- high = mid;
+ public:
+ int singleNonDuplicate(vector<int> &nums) {
+ int low = 0, high = nums.size() - 1;
+ while (low < high) {
+ int mid = low + (high - low) / 2;
+ if ((mid % 2 == 0 && nums[mid] == nums[mid + 1]) || (mid % 2 == 1 && nums[mid] == nums[mid - 1]))
+ low = mid + 1;
+ else
+ high = mid;
+ }
+ return nums[low];
}
- return nums[low];
- }
};
diff --git a/Problems/0542.cpp b/Problems/0542.cpp
@@ -1,46 +1,41 @@
class Solution {
- int m, n;
- vector<pair<int, int>> offset = {
- {-1, 0},
- { 1, 0},
- { 0, -1},
- { 0, 1}
- };
+ int m, n;
+ vector<pair<int, int>> offset = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
- int valid(int sr, int sc) { return sr >= 0 && sr < m && sc >= 0 && sc < n; }
+ int valid(int sr, int sc) { return sr >= 0 && sr < m && sc >= 0 && sc < n; }
-public:
- vector<vector<int>> updateMatrix(vector<vector<int>> &mat) {
- m = mat.size();
- n = mat[0].size();
+ public:
+ vector<vector<int>> updateMatrix(vector<vector<int>> &mat) {
+ m = mat.size();
+ n = mat[0].size();
- vector<vector<int>> res(m, vector<int>(n, INT_MAX));
- queue<pair<int, int>> q;
+ vector<vector<int>> res(m, vector<int>(n, INT_MAX));
+ queue<pair<int, int>> q;
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < n; j++) {
- if (mat[i][j] == 0) {
- res[i][j] = 0;
- q.push({i, j});
+ for (int i = 0; i < m; i++) {
+ for (int j = 0; j < n; j++) {
+ if (mat[i][j] == 0) {
+ res[i][j] = 0;
+ q.push({i, j});
+ }
+ }
}
- }
- }
- while (!q.empty()) {
- auto [sr, sc] = q.front();
- q.pop();
- for (auto &p : offset) {
- int nsr = sr + p.first;
- int nsc = sc + p.second;
- if (valid(nsr, nsc)) {
- if (res[nsr][nsc] > res[sr][sc] + 1) {
- res[nsr][nsc] = res[sr][sc] + 1;
- q.push({nsr, nsc});
- }
+ while (!q.empty()) {
+ auto [sr, sc] = q.front();
+ q.pop();
+ for (auto &p : offset) {
+ int nsr = sr + p.first;
+ int nsc = sc + p.second;
+ if (valid(nsr, nsc)) {
+ if (res[nsr][nsc] > res[sr][sc] + 1) {
+ res[nsr][nsc] = res[sr][sc] + 1;
+ q.push({nsr, nsc});
+ }
+ }
+ }
}
- }
- }
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0543.cpp b/Problems/0543.cpp
@@ -1,35 +1,35 @@
class Solution {
-public:
- int diameterOfBinaryTree(TreeNode *root) {
- unordered_map<TreeNode *, int> um;
- stack<TreeNode *> st;
- int res = 0;
+ public:
+ int diameterOfBinaryTree(TreeNode *root) {
+ unordered_map<TreeNode *, int> um;
+ stack<TreeNode *> st;
+ int res = 0;
- while (root) {
- st.push(root);
- root = root->left;
- }
-
- while (!st.empty()) {
- TreeNode *root = st.top();
- st.pop();
- if (um.find(root) == um.end()) {
- um.insert({root, 1});
- st.push(root);
- root = root->right;
while (root) {
- st.push(root);
- root = root->left;
+ st.push(root);
+ root = root->left;
}
- } else {
- if (!root->left && !root->right) continue;
- int l = um[root->left];
- int r = um[root->right];
- res = max(l + r, res);
- um[root] = 1 + max(l, r);
- }
- }
- return res;
- }
+ while (!st.empty()) {
+ TreeNode *root = st.top();
+ st.pop();
+ if (um.find(root) == um.end()) {
+ um.insert({root, 1});
+ st.push(root);
+ root = root->right;
+ while (root) {
+ st.push(root);
+ root = root->left;
+ }
+ } else {
+ if (!root->left && !root->right) continue;
+ int l = um[root->left];
+ int r = um[root->right];
+ res = max(l + r, res);
+ um[root] = 1 + max(l, r);
+ }
+ }
+
+ return res;
+ }
};
diff --git a/Problems/0547.cpp b/Problems/0547.cpp
@@ -1,44 +1,44 @@
class UnionFind {
- vector<int> root, rank;
- int n;
+ vector<int> root, rank;
+ int n;
-public:
- UnionFind(int n) : n(n), root(n), rank(n, 1) {
- iota(root.begin(), root.end(), 0);
- }
+ public:
+ UnionFind(int n) : n(n), root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); }
- int find(int x) {
- while (x != root[x]) x = root[x] = root[root[x]];
- return x;
- }
+ int find(int x) {
+ while (x != root[x])
+ x = root[x] = root[root[x]];
+ return x;
+ }
- void join(int x, int y) {
- x = find(x), y = find(y);
+ void join(int x, int y) {
+ x = find(x), y = find(y);
- if (x != y) {
- if (rank[x] > rank[y]) swap(x, y);
+ if (x != y) {
+ if (rank[x] > rank[y]) swap(x, y);
- root[x] = y;
- rank[y] += rank[x];
+ root[x] = y;
+ rank[y] += rank[x];
+ }
}
- }
- int count() {
- int cnt = 0;
- for (int i = 0; i < n; i++) cnt += root[i] == i;
- return cnt;
- }
+ int count() {
+ int cnt = 0;
+ for (int i = 0; i < n; i++)
+ cnt += root[i] == i;
+ return cnt;
+ }
};
class Solution {
-public:
- int findCircleNum(vector<vector<int>> &isConnected) {
- int n = isConnected.size();
- UnionFind uf(n);
- for (int i = 0; i < n; i++)
- for (int j = i + 1; j < n; j++)
- if (isConnected[i][j]) uf.join(i, j);
-
- return uf.count();
- }
+ public:
+ int findCircleNum(vector<vector<int>> &isConnected) {
+ int n = isConnected.size();
+ UnionFind uf(n);
+ for (int i = 0; i < n; i++)
+ for (int j = i + 1; j < n; j++)
+ if (isConnected[i][j]) uf.join(i, j);
+
+ return uf.count();
+ }
};
diff --git a/Problems/0556.cpp b/Problems/0556.cpp
@@ -1,24 +1,24 @@
class Solution {
-public:
- int nextGreaterElement(int n) {
- string nums = to_string(n);
+ public:
+ int nextGreaterElement(int n) {
+ string nums = to_string(n);
- int prev = 0;
- stack<int> st;
- for (int i = nums.size() - 1; i >= 0; i--) {
- if (!st.empty() && nums[i] < nums[st.top()]) {
- while (!st.empty() && nums[i] < nums[st.top()]) {
- prev = st.top();
- st.pop();
+ int prev = 0;
+ stack<int> st;
+ for (int i = nums.size() - 1; i >= 0; i--) {
+ if (!st.empty() && nums[i] < nums[st.top()]) {
+ while (!st.empty() && nums[i] < nums[st.top()]) {
+ prev = st.top();
+ st.pop();
+ }
+ swap(nums[i], nums[prev]);
+ reverse(nums.begin() + i + 1, nums.end());
+ break;
+ }
+ st.push(i);
}
- swap(nums[i], nums[prev]);
- reverse(nums.begin() + i + 1, nums.end());
- break;
- }
- st.push(i);
- }
- long long res = stoll(nums);
- return (res > INT_MAX || (int)res == n) ? -1 : (int)res;
- }
+ long long res = stoll(nums);
+ return (res > INT_MAX || (int)res == n) ? -1 : (int)res;
+ }
};
diff --git a/Problems/0557.cpp b/Problems/0557.cpp
@@ -1,15 +1,16 @@
class Solution {
-public:
- string reverseWords(string s) {
- int last = -1;
- for (int k = 0; k <= s.size(); k++) {
- if (k == s.size() || s[k] == ' ') {
- int i = last + 1;
- int j = k - 1;
- while (i < j) swap(s[i++], s[j--]);
- last = k;
- }
+ public:
+ string reverseWords(string s) {
+ int last = -1;
+ for (int k = 0; k <= s.size(); k++) {
+ if (k == s.size() || s[k] == ' ') {
+ int i = last + 1;
+ int j = k - 1;
+ while (i < j)
+ swap(s[i++], s[j--]);
+ last = k;
+ }
+ }
+ return s;
}
- return s;
- }
};
diff --git a/Problems/0559.cpp b/Problems/0559.cpp
@@ -1,18 +1,19 @@
class Solution {
-public:
- int maxDepth(Node *root) {
- if (!root) return 0;
+ public:
+ int maxDepth(Node *root) {
+ if (!root) return 0;
- int lvl;
- queue<Node *> q;
- q.push(root);
- for (lvl = 0; !q.empty(); lvl++) {
- for (int t = q.size(); t > 0; t--) {
- Node *root = q.front();
- q.pop();
- for (Node *c : root->children) q.push(c);
- }
+ int lvl;
+ queue<Node *> q;
+ q.push(root);
+ for (lvl = 0; !q.empty(); lvl++) {
+ for (int t = q.size(); t > 0; t--) {
+ Node *root = q.front();
+ q.pop();
+ for (Node *c : root->children)
+ q.push(c);
+ }
+ }
+ return lvl;
}
- return lvl;
- }
};
diff --git a/Problems/0560.cpp b/Problems/0560.cpp
@@ -1,17 +1,18 @@
class Solution {
-public:
- int subarraySum(vector<int> &nums, int k) {
- int n = nums.size(), res = 0, sum = 0;
- unordered_map<int, int> um;
- vector<int> prefix(n);
- for (int i = 0; i < n; i++) sum = prefix[i] = sum + nums[i];
+ public:
+ int subarraySum(vector<int> &nums, int k) {
+ int n = nums.size(), res = 0, sum = 0;
+ unordered_map<int, int> um;
+ vector<int> prefix(n);
+ for (int i = 0; i < n; i++)
+ sum = prefix[i] = sum + nums[i];
- for (int i = 0; i < n; i++) {
- if (prefix[i] == k) res++;
- if (um.count(prefix[i] - k)) res += um[prefix[i] - k];
- um[prefix[i]]++;
- }
+ for (int i = 0; i < n; i++) {
+ if (prefix[i] == k) res++;
+ if (um.count(prefix[i] - k)) res += um[prefix[i] - k];
+ um[prefix[i]]++;
+ }
- return res;
- }
+ return res;
+ }
};
diff --git a/Problems/0561.cpp b/Problems/0561.cpp
@@ -1,21 +1,22 @@
class Solution {
- const static int length = 20001;
+ const static int length = 20001;
-public:
- int arrayPairSum(vector<int> &nums) {
- int arr[length] = {0};
+ public:
+ int arrayPairSum(vector<int> &nums) {
+ int arr[length] = {0};
- for (int i : nums) arr[i + 10000]++;
+ for (int i : nums)
+ arr[i + 10000]++;
- int res = 0;
- int sub = 0;
- for (int i = 0; i < length; i++) {
- if (!arr[i]) continue;
+ int res = 0;
+ int sub = 0;
+ for (int i = 0; i < length; i++) {
+ if (!arr[i]) continue;
- arr[i] -= sub;
- res += (arr[i] / 2 + arr[i] % 2) * (i - 10000);
- sub = arr[i] % 2;
+ arr[i] -= sub;
+ res += (arr[i] / 2 + arr[i] % 2) * (i - 10000);
+ sub = arr[i] % 2;
+ }
+ return res;
}
- return res;
- }
};
diff --git a/Problems/0563.cpp b/Problems/0563.cpp
@@ -1,18 +1,18 @@
class Solution {
- int res = 0;
+ int res = 0;
- int sum_adding_tilt(TreeNode *root) {
- if (!root) return 0;
- int l = sum_adding_tilt(root->left);
- int r = sum_adding_tilt(root->right);
- res += abs(l - r);
- return l + r + root->val;
- }
+ int sum_adding_tilt(TreeNode *root) {
+ if (!root) return 0;
+ int l = sum_adding_tilt(root->left);
+ int r = sum_adding_tilt(root->right);
+ res += abs(l - r);
+ return l + r + root->val;
+ }
-public:
- int findTilt(TreeNode *root) {
- res = 0;
- sum_adding_tilt(root);
- return res;
- }
+ public:
+ int findTilt(TreeNode *root) {
+ res = 0;
+ sum_adding_tilt(root);
+ return res;
+ }
};
diff --git a/Problems/0566.cpp b/Problems/0566.cpp
@@ -1,20 +1,20 @@
class Solution {
-public:
- vector<vector<int>> matrixReshape(vector<vector<int>> &mat, int r, int c) {
- int n = mat.size(), m = mat[0].size();
- if (m * n != r * c) return mat;
- vector<vector<int>> nmat(r, vector<int>(c));
+ public:
+ vector<vector<int>> matrixReshape(vector<vector<int>> &mat, int r, int c) {
+ int n = mat.size(), m = mat[0].size();
+ if (m * n != r * c) return mat;
+ vector<vector<int>> nmat(r, vector<int>(c));
- int x = 0, y = 0;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < m; j++) {
- nmat[x][y] = mat[i][j];
- y++;
- x += y / c;
- y %= c;
- }
- }
+ int x = 0, y = 0;
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < m; j++) {
+ nmat[x][y] = mat[i][j];
+ y++;
+ x += y / c;
+ y %= c;
+ }
+ }
- return nmat;
- }
+ return nmat;
+ }
};
diff --git a/Problems/0567.cpp b/Problems/0567.cpp
@@ -1 +1 @@
-Formating: Problems/0567.cpp
+Formating : Problems / 0567.cpp
diff --git a/Problems/0572.cpp b/Problems/0572.cpp
@@ -1,47 +1,47 @@
class Solution {
- bool strStr(string haystack, string needle) {
- int m = haystack.size(), n = needle.size();
- vector<int> table(needle.size(), 0);
+ bool strStr(string haystack, string needle) {
+ int m = haystack.size(), n = needle.size();
+ vector<int> table(needle.size(), 0);
- for (int len = 0, j = 1; j < n;) {
- if (needle[j] == needle[len])
- table[j++] = ++len;
- else if (len)
- len = table[len - 1];
- else
- table[j++] = 0;
- }
+ for (int len = 0, j = 1; j < n;) {
+ if (needle[j] == needle[len])
+ table[j++] = ++len;
+ else if (len)
+ len = table[len - 1];
+ else
+ table[j++] = 0;
+ }
- for (int i = 0, j = 0; i < m;) {
- if (haystack[i] == needle[j]) i++, j++;
- if (j == n) return true;
- if (i < m && haystack[i] != needle[j]) j ? j = table[j - 1] : i++;
- }
+ for (int i = 0, j = 0; i < m;) {
+ if (haystack[i] == needle[j]) i++, j++;
+ if (j == n) return true;
+ if (i < m && haystack[i] != needle[j]) j ? j = table[j - 1] : i++;
+ }
- return false;
- }
+ return false;
+ }
- string tree_preorder_string(TreeNode *root) {
- if (!root) return "";
- string res = "";
- stack<TreeNode *> st;
+ string tree_preorder_string(TreeNode *root) {
+ if (!root) return "";
+ string res = "";
+ stack<TreeNode *> st;
- st.push(root);
- while (!st.empty()) {
- TreeNode *root = st.top();
- st.pop();
- res += root ? "_" + to_string(root->val) : "#";
- if (!root) continue;
- st.push(root->right);
- st.push(root->left);
+ st.push(root);
+ while (!st.empty()) {
+ TreeNode *root = st.top();
+ st.pop();
+ res += root ? "_" + to_string(root->val) : "#";
+ if (!root) continue;
+ st.push(root->right);
+ st.push(root->left);
+ }
+ return res;
}
- return res;
- }
-public:
- bool isSubtree(TreeNode *root, TreeNode *subRoot) {
- string tree = tree_preorder_string(root);
- string sub = tree_preorder_string(subRoot);
- return strStr(tree, sub);
- }
+ public:
+ bool isSubtree(TreeNode *root, TreeNode *subRoot) {
+ string tree = tree_preorder_string(root);
+ string sub = tree_preorder_string(subRoot);
+ return strStr(tree, sub);
+ }
};
diff --git a/Problems/0583.cpp b/Problems/0583.cpp
@@ -1,18 +1,17 @@
class Solution {
- vector<vector<int>> dp;
+ vector<vector<int>> dp;
- int solve(const string &s1, const string &s2, int i, int j) {
- if (i == s1.size() && j == s2.size()) return 0;
- if (i == s1.size() || j == s2.size())
- return max(s1.size() - i, s2.size() - j);
- if (dp[i][j] != INT_MAX) return dp[i][j];
- if (s1[i] == s2[j]) return solve(s1, s2, i + 1, j + 1);
- return dp[i][j] = 1 + min(solve(s1, s2, i + 1, j), solve(s1, s2, i, j + 1));
- }
+ int solve(const string &s1, const string &s2, int i, int j) {
+ if (i == s1.size() && j == s2.size()) return 0;
+ if (i == s1.size() || j == s2.size()) return max(s1.size() - i, s2.size() - j);
+ if (dp[i][j] != INT_MAX) return dp[i][j];
+ if (s1[i] == s2[j]) return solve(s1, s2, i + 1, j + 1);
+ return dp[i][j] = 1 + min(solve(s1, s2, i + 1, j), solve(s1, s2, i, j + 1));
+ }
-public:
- int minDistance(const string &word1, const string &word2) {
- dp.resize(size(word1) + 1, vector<int>(size(word2) + 1, INT_MAX));
- return solve(word1, word2, 0, 0);
- }
+ public:
+ int minDistance(const string &word1, const string &word2) {
+ dp.resize(size(word1) + 1, vector<int>(size(word2) + 1, INT_MAX));
+ return solve(word1, word2, 0, 0);
+ }
};
diff --git a/Problems/0589.cpp b