problemscpp
A collection of my answers to algorithm problems in c++.
载入中...
搜索中...
未找到
leetcode.h
浏览该文件的文档.
1#ifndef PROBLEMSCPP_LEETCODE_H
2#define PROBLEMSCPP_LEETCODE_H
3
4#include "templates.h"
5#include <algorithm>
6#include <array>
7#include <bitset>
8#include <functional>
9#include <list>
10#include <map>
11#include <queue>
12#include <random>
13#include <set>
14#include <sstream>
15#include <string>
16#include <unordered_set>
17#include <utility>
18#include <vector>
19
20using namespace std;
21
22namespace leetcode {
23 struct TreeNode {
24 int val;
27
29 : val(0), left(nullptr), right(nullptr) {}
30
31 explicit TreeNode(int x)
32 : val(x), left(nullptr), right(nullptr) {}
33
36
37 bool operator==(const TreeNode & /*node*/) const;
38
39 bool operator!=(const TreeNode & /*node*/) const;
40 };
41
42 struct ListNode {
43 int val;
45
47 : val(0), next(nullptr){};
48
49 explicit ListNode(int x)
50 : val(x), next(nullptr){};
51
53 : val(x), next(next){};
54 };
55
56 class Node {
57 public:
58 int val;
62
64 : val(0), left(nullptr), right(nullptr), next(nullptr) {}
65
66 explicit Node(int _val)
67 : val(_val), left(nullptr), right(nullptr), next(nullptr) {}
68
69 Node(int _val, Node *_left, Node *_right, Node *_next)
70 : val(_val), left(_left), right(_right), next(_next) {}
71 };
72
73 namespace concatenated_words {
74 class Solution {
75 public:
76 static vector<string> findAllConcatenatedWordsInADict(vector<string> & /*words*/);
77 };
78
79 class TrieNode {
80 public:
81 bool is_end;
82 char ch;
83 TrieNode *nexts[26] = {
84 nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
85 nullptr,
86 nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
87 nullptr,
88 nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
89
90 explicit TrieNode(char /*ch*/);
91
92 void insert(const string &str);
93
94 bool dfs(TrieNode * /*root*/, const string & /*str*/, int /*start*/, bool /*flag*/) const;
95 };
96 }// namespace concatenated_words
97
98 namespace excel_sheet_column_number {
99 class Solution {
100 public:
101 static int titleToNumber(const string &columnTitle);
102 };
103 }// namespace excel_sheet_column_number
104
105 namespace excel_sheet_column_title {
106 class Solution {
107 public:
108 static string convertToTitle(int columnNumber);
109 };
110 }// namespace excel_sheet_column_title
111
112 namespace majority_element {
113 class Solution {
114 private:
115 map<int, int> m;
116
117 public:
118 Solution();
119
120 int majorityElement(vector<int> &nums);
121 };
122 }// namespace majority_element
123
124 namespace count_special_quadruplets {
125 class Solution {
126 public:
127 static int countQuadruplets(vector<int> & /*nums*/);
128 };
129 }// namespace count_special_quadruplets
130
131 namespace hand_of_straights {
132 class Solution {
133 public:
134 static bool isNStraightHand(vector<int> &hand, int groupSize);
135 };
136 }// namespace hand_of_straights
137
138 namespace perfect_number {
139 class Solution {
140 public:
141 static bool checkPerfectNumber(int num);
142 };
143 }// namespace perfect_number
144
157
158 class Solution {
159 public:
160 static TreeNode *convertBST(TreeNode *root);
161
162 static FriendTreeNode *copy(TreeNode * /*node*/);
163
164 static void get_sum(FriendTreeNode * /*node*/);
165
166 static void convert(FriendTreeNode * /*sum_node*/);
167 };
168 }// namespace convert_bst_to_greater_tree
169
171 class Solution {
172 public:
173 static vector<vector<int>> construct2DArray(vector<int> &original, int m, int n);
174 };
175 }// namespace convert_1d_array_into_2d_array
176
177 namespace elimination_game {
178 class Solution {
179 public:
180 static int lastRemaining(int /*n*/);
181 };
182 }// namespace elimination_game
183
185 class Solution {
186 public:
187 static bool checkString(const string & /*s*/);
188 };
189 }// namespace check_if_all_as_appears_before_all_bs
190
192 class Solution {
193 public:
194 static int numberOfBeams(vector<string> & /*bank*/);
195
196 static int deviceCount(const string & /*str*/);
197 };
198 }// namespace number_of_laser_beams_in_a_bank
199
200 namespace destroying_asteroids {
201 class Solution {
202 public:
203 static bool asteroidsDestroyed(int mass, vector<int> &asteroids);
204 };
205 }// namespace destroying_asteroids
206
208 class Solution {
209 public:
210 static int maximumInvitations(vector<int> &);
211 };
212 }// namespace maximum_employees_to_be_invited_to_a_meeting
213
214 namespace day_of_the_week {
215 class Solution {
216 public:
217 static string dayOfTheWeek(int day, int month, int year);
218 };
219 }// namespace day_of_the_week
220
224 namespace cat_and_mouse {
225 const int MOUSE_WIN = 1;
226
227 const int CAT_WIN = 2;
228
229 const int DRAW = 0;
230
231 const int MAXN = 51;
232
233 class Solution {
234 public:
235 int n;
236 int dp[MAXN][MAXN][MAXN * 2];
237 vector<vector<int>> graph;
238
239 int catMouseGame(vector<vector<int>> &graph);
240
241 int getResult(int mouse, int cat, int turns);
242
243 void getNextResult(int mouse, int cat, int turns);
244 };
245 }// namespace cat_and_mouse
246
248 class Solution {
249 public:
250 static string modifyString(string s);
251 };
252 }// namespace replace_all_s_to_avoid_consecutive_repeating_characters
253
257 namespace simplify_path {
258 class Solution {
259 public:
260 static string simplifyPath(const string &path);
261 };
262 }// namespace simplify_path
263
268 class Solution {
269 public:
270 static int maxDepth(const string &s);
271 };
272 }// namespace maximum_nesting_depth_of_the_parentheses
273
275 namespace gray_code {
276 class Solution {
277 public:
278 static vector<int> grayCode(int n);
279 };
280 }// namespace gray_code
281
284 class Solution {
285 public:
286 static bool checkValid(vector<vector<int>> &matrix);
287 };
288 }// namespace check_if_every_row_and_column_contains_all_numbers
289
292 class Solution {
293 public:
294 static int minSwaps(vector<int> &nums);
295 };
296 }// namespace minimum_swaps_to_group_all_1s_together_ii
297
300 class Solution {
301 public:
302 static int wordCount(vector<string> &startWords, vector<string> &targetWords);
303
304 static unsigned int str2bin(const string & /*str*/);
305 };
306 }// namespace count_words_obtained_after_adding_a_letter
307
309 namespace slowest_key {
310 class Solution {
311 public:
312 static char slowestKey(vector<int> &releaseTimes, string keysPressed);
313 };
314 }// namespace slowest_key
315
319 namespace additive_number {
320 class Solution {
321 public:
322 static bool isAdditiveNumber(string num);
331 static bool dfs(unsigned long long n1, unsigned long long n2, const char * /*nums*/, unsigned short length, unsigned short current);
338 static unsigned long long str2ui(const char * /*str*/, unsigned short start, unsigned short length);
339
346 static bool equal(string /*sum*/, const char * /*nums*/, unsigned short start, unsigned short length);
347 };
348 }// namespace additive_number
349
352 class Solution {
353 public:
354 static string decodeCiphertext(string encodedText, int rows);
360 static string rtrim(string &s);
361 };
362 }// namespace decode_the_slanted_ciphertext
363
365 namespace escape_a_large_maze {
366 struct point {
367 unsigned int x;
368 unsigned int y;
369 unsigned int distance;
371
373 : x(0), y(0), distance(0), target(nullptr){};
374
375 point(unsigned int x, unsigned int y, int distance, point *target)
376 : x(x), y(y), distance(distance), target(target){};
377 bool operator<(const point &p) const;
378 bool operator==(const point &p) const;
379 };
380
381 struct point_hash {
382 size_t operator()(const point &p) const;
383 };
384
385 class Solution {
386 public:
387 static bool isEscapePossible(vector<vector<int>> &blocked, vector<int> &source, vector<int> &target);
388
395 static unsigned int search(unordered_set<point, point_hash> &block_set, point *source, point *target, unsigned int limit);
396 };
397 }// namespace escape_a_large_maze
398
403 class Solution {
404 public:
405 static bool increasingTriplet(vector<int> &nums);
406 };
407 }// namespace increasing_triplet_subsequence
408
413 class Solution {
414 public:
415 static int dominantIndex(vector<int> &nums);
416 };
417 }// namespace largest_number_at_least_twice_of_others
418
421 struct pair {
422 int u;
423 int v;
424
425 pair(int u, int v)
426 : u(u), v(v){};
427 bool operator<(const pair & /*p*/) const;
428 };
429
430 class Solution {
431 public:
432 static vector<vector<int>> kSmallestPairs(vector<int> &nums1, vector<int> &nums2, int k);
433 };
434 }// namespace find_k_pairs_with_smallest_sums
435
439 namespace permutations {
440 class Solution {
441 public:
442 static vector<vector<int>> permute(vector<int> &nums);
443 };
444 }// namespace permutations
445
448 class Solution {
449 public:
450 static int totalMoney(int n);
451 };
452 }// namespace calculate_money_in_leetcode_bank
453
457 namespace linked_list_random_node {
458 class Solution {
459 private:
461
462 public:
464 : head(head){};
465 [[nodiscard]] int getRandom() const;
466 };
467
468 }// namespace linked_list_random_node
469
473 namespace divide_a_string_into_groups_of_size_k {
474 class Solution {
475 public:
476 static vector<string> divideString(const string &s, int k, char fill);
477 };
478 }// namespace divide_a_string_into_groups_of_size_k
479
484 class Solution {
485 public:
486 static int minMoves(int target, int maxDoubles);
487 };
488 }// namespace minimum_moves_to_reach_target_score
489
494 class Solution {
495 public:
496 static long long mostPoints(vector<vector<int>> &questions);
497 };
498 }// namespace solving_questions_with_brainpower
499
504 class Solution {
505 public:
506 static long long maxRunTime(int n, vector<int> &batteries);
507 };
508 }// namespace maximum_running_time_of_n_computers
509
511 namespace coun_vowels_permutation {
512 class Solution {
513 public:
514 static int countVowelPermutation(int n);
515 };
516 }// namespace coun_vowels_permutation
517
522 namespace minimum_time_difference {
523 class Solution {
524 public:
525 static int findMinDifference(vector<string> &timePoints);
526 };
527 }// namespace minimum_time_difference
528
530 namespace contains_duplicate_ii {
531 class Solution {
532 public:
533 static bool containsNearbyDuplicate(vector<int> &nums, int k);
534 };
535 }// namespace contains_duplicate_ii
536
538 namespace stone_game_ix {
539 class Solution {
540 public:
541 static bool stoneGameIX(vector<int> &stones);
542 };
543 }// namespace stone_game_ix
544
548 namespace jump_game_iv {
549 class Solution {
550 public:
551 static int minJumps(vector<int> &arr);
552 };
553 }// namespace jump_game_iv
554
557 class Solution {
558 public:
559 static int removePalindromeSub(string s);
560 };
561 }// namespace remove_palindromic_subsequences
562
564 namespace UhWRSj {
565 struct TrieNode {
566 char ch;
567 TrieNode *next[26] = {};
569
571 : ch(0), endroot(false){};
572
573 explicit TrieNode(char ch)
574 : ch(ch), endroot(false){};
575 void insert(const string &str);
576 [[nodiscard]] string get_prefix(string root, const string &str) const;
577 };
578
579 class Solution {
580 public:
581 static string replaceWords(vector<string> &dictionary, const string &sentence);
582 };
583 }// namespace UhWRSj
584
589 class Solution {
590 public:
591 static int minimumCost(vector<int> &cost);
592 };
593 }// namespace minimum_cost_of_buying_candies_with_discount
594
599 class Solution {
600 public:
601 static int numberOfArrays(vector<int> &differences, int lower, int upper);
602 };
603 }// namespace count_the_hidden_sequences
604
609 struct item {
611 int price;
612 int row;
613 int col;
614
615 item(int distance, int price, int row, int col)
617 bool operator<(const item & /*i*/) const;
618 };
619
620 class Solution {
621 public:
622 static vector<vector<int>> highestRankedKItems(vector<vector<int>> &grid, vector<int> &pricing, vector<int> &start, int k);
623 };
624 }// namespace k_highest_ranked_items_within_a_price_range
625
630 class Solution {
631 public:
632 static int numberOfWays(string corridor);
633 };
634 }// namespace number_of_ways_to_divide_a_long_corridor
635
640 class Solution {
641 public:
642 static int countElements(vector<int> &nums);
643 };
644 }// namespace count_elements_with_strictly_smaller_and_greater_elements
645
650 class Solution {
651 public:
652 static vector<int> rearrangeArray(vector<int> &nums);
653 };
654 }// namespace rearrange_array_elements_by_sign
655
660 class Solution {
661 public:
662 static vector<int> findLonely(vector<int> &nums);
663 };
664 }// namespace find_all_lonely_numbers_in_the_array
665
670 struct msg {
672 bool good;
673
674 msg(int person, bool good)
675 : person(person), good(good){};
676 };
677
678 class Solution {
679 public:
680 static int maximumGood(vector<vector<int>> &statements);
681 static pair<int, unordered_map<int, bool>> dfs(vector<vector<int>> &statements, unordered_map<int, bool> um, queue<msg> que);
682 };
683 }// namespace maximum_good_people_based_on_statements
684
688 namespace stock_price_fluctuation {
696 multiset<int> ms;
697 map<int, int> m;
698
699 public:
700 StockPrice();
701 void update(int timestamp, int price);
702 [[nodiscard]] int current() const;
703 [[nodiscard]] int maximum() const;
704 [[nodiscard]] int minimum() const;
705 };
706 }// namespace stock_price_fluctuation
707
712 struct status {
714 int time;
715
718 bool operator<(const status &s) const;
719 };
720
721 class Solution {
722 public:
723 static int secondMinimum(int n, vector<vector<int>> &edges, int time, int change);
724 };
725 }// namespace second_minimum_time_to_reach_destination
726
729 class Solution {
730 public:
731 static int numberOfMatches(int n);
732 };
733 }// namespace count_of_matches_in_tournament
734
741 namespace detect_squares {
743 multiset<pair<int, int>> ms;
744
745 public:
747 void add(vector<int> point);
748 [[nodiscard]] int count(vector<int> point) const;
749 };
750 }// namespace detect_squares
751
754 class Solution {
755 public:
756 static int countValidWords(const string &sentence);
757 };
758 }// namespace number_of_valid_words_in_a_sentence
759
762 class Solution {
763 public:
764 static int numberOfWeakCharacters(vector<vector<int>> &properties);
765 };
766 }// namespace the_number_of_weak_characters_in_the_game
767
769 namespace pattern_matching_lcci {
770 class Solution {
771 public:
772 static bool patternMatching(const string &pattern, const string &value);
773 };
774 }// namespace pattern_matching_lcci
775
779 namespace map_of_highest_peak {
780 class Solution {
781 public:
782 static vector<vector<int>> highestPeak(vector<vector<int>> &isWater);
783 };
784 }// namespace map_of_highest_peak
785
790 class Solution {
791 public:
792 static vector<string> uncommonFromSentences(const string &s1, const string &s2);
793 };
794 }// namespace uncommon_words_from_two_sentences
795
800 class Solution {
801 public:
802 static int findFinalValue(vector<int> &nums, int original);
803 };
804 }// namespace keep_multiplying_found_values_by_two
805
810 class Solution {
811 public:
812 static vector<int> maxScoreIndices(vector<int> &nums);
813 };
814 }// namespace all_divisions_with_the_highest_score_of_a_binary_array
815
820 class Solution {
821 public:
822 static string subStrHash(string s, int power, int modulo, int k, int hashValue);
823 };
824 }// namespace find_substring_with_given_hash_value
825
829 namespace groups_of_strings {
830 class Solution {
831 int groups = 0;
832 unsigned int max_size = 1;
833 unordered_map<unsigned int, unsigned int> parent = unordered_map<unsigned int, unsigned int>();
834 unordered_map<unsigned int, unsigned int> rank = unordered_map<unsigned int, unsigned int>();
835 unordered_map<unsigned int, unsigned int> size = unordered_map<unsigned int, unsigned int>();
836
837 public:
838 vector<int> groupStrings(vector<string> &words);
839 static unsigned int compress(const string &word);
840 void insert(unsigned int num);
841 unsigned int find(unsigned int x);
842 void to_union(unsigned int x1, unsigned int x2);
843 };
844 }// namespace groups_of_strings
845
848 class Solution {
849 public:
850 static int numberOfSteps(int num);
851 };
852 }// namespace number_of_steps_to_reduce_a_number_to_zero
853
855 namespace longest_nice_substring {
856 class Solution {
857 public:
858 static string longestNiceSubstring(const string &s);
859 static pair<int, int> dfs(string s, int start, int end);
860 };
861 }// namespace longest_nice_substring
862
864 namespace reverse_prefix_of_word {
865 class Solution {
866 public:
867 static string reversePrefix(string word, char ch);
868 };
869 }// namespace reverse_prefix_of_word
870
875 class Solution {
876 public:
877 static int findMinFibonacciNumbers(int k);
878 static int find_min(set<int, greater<>> &fibb, int k, set<int, greater<>>::iterator begin);
879 };
880 }// namespace find_the_minimum_number_of_fibonacci_numbers_whose_sum_is_k
881
884 class Solution {
885 public:
886 static int countGoodRectangles(vector<vector<int>> &rectangles);
887 };
888 }// namespace number_of_rectangles_that_can_form_the_largest_square
889
891 namespace path_with_maximum_gold {
892 class Solution {
893 public:
894 static int getMaximumGold(vector<vector<int>> &grid);
895 static int get_sum(int current, int x, int y, int m, int n, vector<vector<int>> &grid, bool **occupied);
896 };
897 }// namespace path_with_maximum_gold
898
903 class Solution {
904 public:
905 static int minimumSum(int num);
906 };
907 }// namespace minimum_sum_of_four_digit_number_after_splitting_digits
908
913 class Solution {
914 public:
915 static vector<int> pivotArray(vector<int> &nums, int pivot);
916 };
917 }// namespace partition_array_according_to_given_pivot
918
923 class Solution {
924 public:
925 static int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds);
926 static int get_cost(int startAt, int moveCost, int pushCost, const int num[4]);
927 };
928 }// namespace minimum_cost_to_set_cooking_time
929
934 class Solution {
935 public:
936 static long long minimumDifference(vector<int> &nums);
937 };
938 }// namespace minimum_difference_in_sums_after_removal_of_elements
939
943 namespace sum_of_unique_elements {
944 class Solution {
945 public:
946 static int sumOfUnique(vector<int> &nums);
947 };
948 }// namespace sum_of_unique_elements
949
954 class Solution {
955 public:
956 static vector<int> sortEvenOdd(vector<int> &nums);
957 };
958 }// namespace sort_even_and_odd_indices_independently
959
964 class Solution {
965 public:
966 static long long smallestNumber(long long num);
967 };
968 }// namespace smallest_value_of_the_rearranged_number
969
973 namespace design_bitset {
974 class Bitset {
975 int size = 0;
976 set<unsigned int> *one1;
977 set<unsigned int> *zero0;
978
979 public:
983 explicit Bitset(int size);
987 void fix(int idx) const;
991 void unfix(int idx) const;
995 void flip();
999 [[nodiscard]] bool all() const;
1003 [[nodiscard]] bool one() const;
1007 [[nodiscard]] int count() const;
1011 [[nodiscard]] string toString() const;
1012 };
1013 }// namespace design_bitset
1014
1016 namespace longest_happy_string {
1017 class Solution {
1018 public:
1019 static string longestDiverseString(int a, int b, int c);
1020 static void sort(char ch[3], int a, int b, int c);
1021 static int *get_p(char ch, int *a, int *b, int *c);
1022 };
1023 }// namespace longest_happy_string
1024
1026 namespace grid_illumination {
1027 struct pair_hash {
1028 unsigned long long operator()(const pair<int, int> & /*p*/) const;
1029 };
1030
1031 class Solution {
1032 public:
1033 static vector<int> gridIllumination(int n, vector<vector<int>> &lamps, vector<vector<int>> &queries);
1034 };
1035 }// namespace grid_illumination
1036
1039 class Solution {
1040 public:
1041 static int countKDifference(vector<int> &nums, int k);
1042 };
1043 }// namespace count_number_of_pairs_with_absolute_difference_k
1044
1046 namespace simplified_fractions {
1047 class Solution {
1048 public:
1049 static vector<string> simplifiedFractions(int n);
1050 static int gcd(int m, int n);
1051 };
1052 }// namespace simplified_fractions
1053
1058 class Solution {
1059 public:
1060 static int minimumDifference(vector<int> &nums, int k);
1061 };
1062 }// namespace minimum_difference_between_highest_and_lowest_of_k_scores
1063
1065 namespace number_of_enclaves {
1066 class Solution {
1067 public:
1068 static int numEnclaves(vector<vector<int>> &grid);
1069 };
1070 }// namespace number_of_enclaves
1071
1075 namespace maximum_number_of_balloons {
1076 class Solution {
1077 public:
1078 static int maxNumberOfBalloons(const string &text);
1079 };
1080 }// namespace maximum_number_of_balloons
1081
1085 namespace swap_adjacent_in_lr_string {
1086 class Solution {
1087 public:
1088 static bool canTransform(const string &start, const string &end);
1089 };
1090 }// namespace swap_adjacent_in_lr_string
1091
1096 class Solution {
1097 public:
1098 static int countOperations(int num1, int num2);
1099 };
1100 }// namespace count_operations_to_obtain_zero
1101
1106 class Solution {
1107 public:
1108 static int minimumOperations(vector<int> &nums);
1109 };
1110 }// namespace minimum_operations_to_make_the_array_alternating
1111
1116 class Solution {
1117 public:
1118 static long long minimumRemoval(vector<int> &beans);
1119 };
1120 }// namespace removing_minimum_number_of_magic_beans
1121
1125 namespace maximum_and_sum_of_array {
1126 class Solution {
1127 public:
1128 static int maximumANDSum(vector<int> &nums, int numSlots);
1129 };
1130 }// namespace maximum_and_sum_of_array
1131
1134 class Solution {
1135 public:
1136 static int singleNonDuplicate(vector<int> &nums);
1137 };
1138 }// namespace single_element_in_a_sorted_array
1139
1140
1142 namespace lucky_numbers_in_a_matrix {
1143 class Solution {
1144 public:
1145 static vector<int> luckyNumbers(vector<vector<int>> &matrix);
1146 };
1147 }// namespace lucky_numbers_in_a_matrix
1148
1151 class Solution {
1152 public:
1153 static int checkWays(vector<vector<int>> &pairs);
1154 };
1155 }// namespace number_of_ways_to_reconstruct_a_tree
1156
1158 namespace find_center_of_star_graph {
1159 class Solution {
1160 public:
1161 static int findCenter(vector<vector<int>> &edges);
1162 };
1163 }// namespace find_center_of_star_graph
1164
1167 struct status {
1168 int k;
1169 int row;
1171
1172 status(int k, int row, int column)
1173 : k(k), row(row), column(column){};
1174 };
1175
1177 unsigned int operator()(const status & /*s*/) const;
1178 };
1179
1181 bool operator()(const status & /*s1*/, const status & /*s2*/) const;
1182 };
1183
1184 class Solution {
1185 unordered_map<status, double, status_hash, status_equal> um = unordered_map<status, double, status_hash, status_equal>();
1186
1187 public:
1188 double knightProbability(int n, int k, int row, int column);
1189 };
1190 }// namespace knight_probability_in_chessboard
1191
1193 namespace pancake_sorting {
1194 class Solution {
1195 public:
1196 static vector<int> pancakeSort(vector<int> &arr);
1197 };
1198 }// namespace pancake_sorting
1199
1202 class Solution {
1203 public:
1204 static int countPairs(vector<int> &nums, int k);
1205 };
1206 }// namespace count_equal_and_divisible_pairs_in_an_array
1207
1210 class Solution {
1211 public:
1212 static vector<long long> sumOfThree(long long num);
1213 };
1214 }// namespace find_three_consecutive_integers_that_sum_to_a_given_number
1215
1218 class Solution {
1219 public:
1220 static vector<long long> maximumEvenSplit(long long finalSum);
1221 };
1222 }// namespace maximum_split_of_positive_even_integers
1223
1226 template<class T> class FenwickTree {
1227 int limit{};
1228 vector<T> arr;
1229
1230 static int lowbit(int x) { return x & -x; }
1231
1232 public:
1233 explicit FenwickTree(int limit) {
1234 this->limit = limit;
1235 arr = vector<T>(limit + 1);
1236 }
1237
1238 void update(int idx, T delta) {
1239 for(; idx <= limit; idx += lowbit(idx)) {
1240 arr[idx] += delta;
1241 }
1242 }
1243
1244 T query(int idx) {
1245 T ans = 0;
1246 for(; idx > 0; idx -= lowbit(idx)) {
1247 ans += arr[idx];
1248 }
1249 return ans;
1250 }
1251 };
1252
1253 class Solution {
1254 public:
1255 static long long goodTriplets(vector<int> &nums1, vector<int> &nums2);
1256 };
1257 }// namespace count_good_triplets_in_an_array
1258
1261 class Solution {
1262 public:
1263 static int countEven(int num);
1264 };
1265 }// namespace count_integers_with_even_digit_sum
1266
1269 class Solution {
1270 public:
1271 static ListNode *mergeNodes(ListNode *head);
1272 };
1273 }// namespace merge_nodes_in_between_zeros
1274
1277 class Solution {
1278 public:
1279 static string repeatLimitedString(const string &s, int repeatLimit);
1280 };
1281 }// namespace construct_string_with_repeat_limit
1282
1285 class Solution {
1286 public:
1287 static long long coutPairs(vector<int> &nums, int k);
1288 };
1289 }// namespace count_array_pairs_divisible_by_k
1290
1295 class Solution {
1296 public:
1297 static bool isOneBitCharacter(vector<int> &bits);
1298 };
1299 }// namespace leetcode717_1_bit_and_2_bit_characters
1300
1304 namespace longest_mountain_in_array {
1305 class Solution {
1306 public:
1307 static int longestMountain(vector<int> &arr);
1308 };
1309 }// namespace longest_mountain_in_array
1310
1312 namespace push_dominoes {
1313 class Solution {
1314 public:
1315 static string pushDominoes(string dominoes);
1316 };
1317 }// namespace push_dominoes
1318
1320 namespace the_number_of_good_subsets {
1321 class Solution {
1322 private:
1323 static constexpr array<int, 10> primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
1324 static constexpr int num_max = 30;
1325 static constexpr int mod = 1000000007;
1326 static constexpr int mask_max = 1 << primes.size();
1327
1328 public:
1329 static int numberOfGoodSubsets(vector<int> &nums);
1330 };
1331 }// namespace the_number_of_good_subsets
1332
1334 namespace reverse_only_letters {
1335 class Solution {
1336 public:
1337 static string reverseOnlyLetters(string s);
1338 };
1339 }// namespace reverse_only_letters
1340
1342 namespace where_will_the_ball_fall {
1343 class Solution {
1344 public:
1345 static vector<int> findBall(vector<vector<int>> &grid);
1346 };
1347 }// namespace where_will_the_ball_fall
1348
1351 class Solution {
1352 public:
1353 static string complexNumberMultiply(const string &num1, const string &num2);
1354 };
1355 }// namespace complex_number_multiplication
1356
1359 class Solution {
1360 public:
1361 static int maximumDifference(vector<int> &nums);
1362 };
1363 }// namespace maximum_difference_between_increasing_elements
1364
1368 namespace optimal_division {
1369 class Solution {
1370 public:
1371 static string optimalDivision(vector<int> &nums);
1372 };
1373 }// namespace optimal_division
1374
1379 class Solution {
1380 public:
1381 static int prefixCount(vector<string> &words, string pref);
1382 };
1383 }// namespace counting_words_with_a_given_prefix
1384
1389 class Solution {
1390 public:
1391 static int minSteps(const string &s, const string &t);
1392 };
1393 }// namespace minimum_number_of_steps_to_make_two_strings_anagram_ii
1394
1399 class Solution {
1400 public:
1401 static long long minimumTime(vector<int> &time, int totalTrips);
1402 };
1403 }// namespace minimum_time_to_complete_trips
1404
1409 class Solution {
1410 public:
1411 static int minimumFinishTime(vector<vector<int>> &tires, int changeTime, int numLaps);
1412 };
1413 }// namespace minimum_time_to_finish_the_race
1414
1417 class Solution {
1418 public:
1419 static int maximumRequests(int n, vector<vector<int>> &requests);
1420 };
1421 }// namespace maximum_number_of_achievable_transfer_requests
1422
1424 namespace zigzag_conversion {
1425 class Solution {
1426 public:
1427 static string convert(string s, int numRows);
1428 };
1429 }// namespace zigzag_conversion
1430
1432 namespace find_the_closest_palindrome {
1433 class Solution {
1434 public:
1435 static string nearestPalindromic(const string &n);
1436 };
1437 }// namespace find_the_closest_palindrome
1438
1440 namespace add_digits {
1441 class Solution {
1442 public:
1443 static int addDigits(int num);
1444 };
1445 }// namespace add_digits
1446
1448 namespace sum_of_subarray_ranges {
1449 class Solution {
1450 public:
1451 static long long subArrayRanges(vector<int> &nums);
1452 };
1453 }// namespace sum_of_subarray_ranges
1454
1459 class Solution {
1460 public:
1461 static int findLUSlength(const string &a, const string &b);
1462 };
1463 }// namespace longest_uncommon_subsequence_i
1464
1469 class Solution {
1470 public:
1471 static int mostFrequent(vector<int> &nums, int key);
1472 };
1473 }// namespace most_frequent_number_following_key_in_an_array
1474
1478 namespace sort_the_jumbled_numbers {
1479 struct cmp {
1480 bool operator()(const tuple<int, int, int> &s1, const tuple<int, int, int> &s2) const {
1481 auto [i1, num1, rev1] = s1;
1482 auto [i2, num2, rev2] = s2;
1483 if(rev1 != rev2) {
1484 return rev1 < rev2;
1485 }
1486 return i1 < i2;
1487 }
1488 };
1489
1490 class Solution {
1491 public:
1492 static vector<int> sortJumbled(vector<int> &mapping, vector<int> &nums);
1493 };
1494 }// namespace sort_the_jumbled_numbers
1495
1500 class Solution {
1501 unordered_map<int, unordered_set<int>> nexts;
1502 unordered_map<int, set<int>> ancestors;
1503
1504 public:
1505 vector<vector<int>> getAncestors(int n, vector<vector<int>> &edges);
1506 void dfs(bool *dfsd, int v, int i);
1507 };
1508 }// namespace all_ancestors_of_a_node_in_a_directed_acyclic_graph
1509
1514 class Solution {
1515 public:
1516 static int minMovesToMakePalindrome(string s);
1517 };
1518 }// namespace minimum_number_of_moves_to_make_palindrome
1519
1524 class Solution {
1525 public:
1526 static vector<string> cellsInRange(const string &s);
1527 };
1528 }// namespace cells_in_a_range_on_an_excel_sheet
1529
1534 class Solution {
1535 public:
1536 static long long minimalKSum(vector<int> &nums, int k);
1537 };
1538 }// namespace append_k_integers_with_minimal_sum
1539
1544 class Solution {
1545 public:
1546 static TreeNode *createBinaryTree(vector<vector<int>> &descriptions);
1547 };
1548 }// namespace create_binary_tree_from_descriptions
1549
1554 class Solution {
1555 public:
1556 static vector<int> replaceNonCoprimes(vector<int> &nums);
1557 };
1558 }// namespace replace_non_coprime_numbers_in_array
1559
1564 class Solution {
1565 public:
1566 static vector<int> goodDaysToRobBank(vector<int> &security, int time);
1567 };
1568 }// namespace find_good_days_to_rob_the_bank
1569
1571 namespace base_7 {
1572 class Solution {
1573 public:
1574 static string convertToBase7(int num);
1575 };
1576 }// namespace base_7
1577
1579 namespace plates_between_candles {
1580 class Solution {
1581 public:
1582 static vector<int> platesBetweenCandles(string s, vector<vector<int>> &queries);
1583 };
1584 }// namespace plates_between_candles
1585
1588 class Solution {
1589 public:
1590 static int bestRotation(vector<int> &nums);
1591 };
1592 }// namespace smallest_rotation_with_highest_score
1593
1596 class Node {
1597 public:
1598 int val{};
1599 vector<Node *> children;
1600 Node() = default;
1601
1602 explicit Node(int _val)
1603 : val(_val) {}
1604
1605 Node(int _val, vector<Node *> _children)
1606 : val(_val), children(std::move(std::move(_children))) {}
1607 };
1608
1609 class Solution {
1610 public:
1611 static vector<int> preorder(Node *root);
1612 };
1613 }// namespace n_ary_tree_preorder_traversal
1614
1617 class TreeNode {
1618 private:
1619 int val;
1620 int count = 0;
1621 vector<TreeNode *> children;
1622 TreeNode *parent = nullptr;
1623
1624 public:
1625 explicit TreeNode(int val)
1626 : val(val){};
1627 void add_child(TreeNode *node);
1628 [[nodiscard]] const vector<TreeNode *> &get_children() const;
1629 [[nodiscard]] int get_count() const;
1630 [[nodiscard]] TreeNode *get_parent() const;
1631 int dfs();
1632 };
1633
1634 class Solution {
1635 public:
1636 static int countHighestScoreNodes(vector<int> &parents);
1637 };
1638 }// namespace count_nodes_with_the_highest_score
1639
1642 class Node {
1643 public:
1644 int val{};
1645 vector<Node *> children;
1646 Node() = default;
1647
1648 explicit Node(int _val)
1649 : val(_val) {}
1650
1651 Node(int _val, vector<Node *> _children)
1652 : val(_val), children(std::move(std::move(_children))) {}
1653 };
1654
1655 class Solution {
1656 public:
1657 static vector<int> postorder(Node *root);
1658 };
1659 }// namespace n_ary_tree_postorder_traversal
1660
1664 namespace max_area_of_island {
1666 private:
1667 int m;
1668 int n;
1669 unordered_map<pair<int, int>, pair<int, int>, function<unsigned int(const pair<int, int> &)>> parent;
1670 unordered_map<pair<int, int>, int, function<unsigned int(const pair<int, int> &)>> size;
1671 unordered_map<pair<int, int>, int, function<unsigned int(const pair<int, int> &)>> rank;
1672
1673 public:
1674 UnionFind(int m, int n);
1675 pair<int, int> find(pair<int, int> val);
1676 void merge(pair<int, int> a, pair<int, int> b);
1677 bool same(pair<int, int> a, pair<int, int> b);
1678 [[nodiscard]] bool contains(pair<int, int> p) const;
1679 int get_size(pair<int, int> p);
1680 };
1681
1682 class Solution {
1683 public:
1684 static int maxAreaOfIsland(vector<vector<int>> &grid);
1685 };
1686 }// namespace max_area_of_island
1687
1690 class Solution {
1691 public:
1692 static vector<int> findKDistantIndices(vector<int> &nums, int key, int k);
1693 };
1694 }// namespace find_all_k_distant_indices_in_an_array
1695
1698 class Solution {
1699 public:
1700 static int digArtifacts(int n, vector<vector<int>> &artifacts, vector<vector<int>> &dig);
1701 };
1702 }// namespace count_artifacts_that_can_be_extracted
1703
1706 class Solution {
1707 public:
1708 static int maximumTop(vector<int> &nums, int k);
1709 };
1710 }// namespace maximize_the_topmost_element_after_k_moves
1711
1714 class Solution {
1715 public:
1716 static long long minimumWeight(int n, vector<vector<int>> &edges, int src1, int src2, int dest);
1717 static void calc_dist(int s, vector<pair<int, int>> *graph, vector<long long int> &dist);
1718 };
1719 }// namespace minimum_weighted_subgraph_with_the_required_paths
1720
1722 namespace utf_8_validation {
1723 class Solution {
1724 public:
1725 static bool validUtf8(vector<int> &data);
1726 };
1727 }// namespace utf_8_validation
1728
1731 class Solution {
1732 public:
1733 static vector<string> findRestaurant(vector<string> &list1, vector<string> &list2);
1734 };
1735 }// namespace minimum_index_sum_of_two_lists
1736
1739 class Solution {
1740 public:
1741 static int countMaxOrSubsets(vector<int> &nums);
1742 static int dfs(int current, int target, vector<int> nums);
1743 };
1744 }// namespace count_number_of_maximum_bitwise_or_subsets
1745
1747 namespace all_oone_data_structure {
1748 class AllOne {
1749 int max = 0;
1750 int min = 50000;
1751 unordered_map<string, int> str_count;
1752 map<int, unordered_set<string>> count_str;
1753
1754 public:
1756 AllOne();
1758 void inc(const string &key);
1760 void dec(const string &key);
1763 string getMaxKey();
1766 string getMinKey();
1767 };
1768 }// namespace all_oone_data_structure
1769
1771 namespace longest_word_in_dictionary {
1772 class Solution {
1773 public:
1774 static string longestWord(vector<string> &words);
1775 static string dfs(const string &str, TrieNode *node);
1776 };
1777 }// namespace longest_word_in_dictionary
1778
1780 namespace simple_bank_system {
1781 class Bank {
1782 unordered_map<int, long long> accounts;
1783
1784 public:
1786 explicit Bank(vector<long long> &balance);
1789 bool transfer(int account1, int account2, long long money);
1792 bool deposit(int account, long long money);
1795 bool withdraw(int account, long long money);
1796 };
1797 }// namespace simple_bank_system
1798
1801 class Solution {
1802 public:
1803 static string tree2str(TreeNode *root);
1804 };
1805 }// namespace construct_string_from_binary_tree
1806
1809 class Solution {
1810 public:
1811 static long long maximumSubsequenceCount(string text, string pattern);
1812 };
1813 }// namespace maximize_number_of_subsequences_in_a_string
1814
1817 class Solution {
1818 public:
1819 static int halveArray(vector<int> &nums);
1820 };
1821 }// namespace minimum_operations_to_halve_array_sum
1822
1825 class Solution {
1826 public:
1827 static int minimumWhiteTiles(string floor, int numCarpets, int carpetLen);
1828 };
1829 }// namespace minimum_white_tiles_after_covering_with_carpets
1830
1833 class Solution {
1834 public:
1835 static int countHillValley(vector<int> &nums);
1836 };
1837 }// namespace count_hills_and_valleys_in_an_array
1838
1840 namespace count_collisions_on_a_road {
1841 class Solution {
1842 public:
1843 static int countCollisions(const string &directions);
1844 };
1845 }// namespace count_collisions_on_a_road
1846
1849 class Solution {
1850 public:
1851 static vector<int> maximumBobPoints(int numArrows, vector<int> &aliceArrows);
1852 };
1853 }// namespace maximum_points_in_an_archery_competition
1854
1857 struct Node {
1858 int num;
1859 int time = 0;
1861 unordered_set<int> linked = {};
1862
1864 : num(num), patience(patience) {}
1865 };
1866
1867 class Solution {
1868 public:
1869 static int networkBecomesIdle(vector<vector<int>> &edges, vector<int> &patience);
1870 };
1871 }// namespace the_time_when_the_network_becomes_idle
1872
1874 namespace two_sum_iv_input_is_a_bst {
1875 class Solution {
1876 public:
1877 static bool findTarget(TreeNode *root, int k);
1878 };
1879 }// namespace two_sum_iv_input_is_a_bst
1880
1883 class Solution {
1884 public:
1885 static bool winnerOfGame(string colors);
1886 };
1887 }// namespace remove_colored_pieces_if_both_neighbors_are_the_same_color
1888
1893 class Solution {
1894 public:
1895 static int findKthNumber(int n, int k);
1896 static int getSteps(int curr, long n);
1897 };
1898 }// namespace k_th_smallest_in_lexicographical_order
1899
1901 namespace image_smoother {
1902 class Solution {
1903 public:
1904 static vector<vector<int>> imageSmoother(vector<vector<int>> &img);
1905 };
1906 }// namespace image_smoother
1907
1909 namespace factorial_trailing_zeroes {
1910 class Solution {
1911 public:
1912 static int trailingZeroes(int n);
1913 };
1914 }// namespace factorial_trailing_zeroes
1915
1917 namespace baseball_game {
1918 class Solution {
1919 public:
1920 static int calPoints(vector<string> &ops);
1921 };
1922 }// namespace baseball_game
1923
1928 class Solution {
1929 public:
1930 static int minDeletion(vector<int> &nums);
1931 };
1932 }// namespace minimum_deletions_to_make_array_beautiful
1933
1938 unsigned long long qmi(unsigned long long m, unsigned long long k);
1939
1940 class Solution {
1941 public:
1942 static vector<long long> kthPalindrome(vector<int> &queries, int intLength);
1943 };
1944 }// namespace find_palindrome_with_fixed_length
1945
1949 namespace find_missing_observations {
1950 class Solution {
1951 public:
1952 static vector<int> missingRolls(vector<int> &rolls, int mean, int n);
1953 };
1954 }// namespace find_missing_observations
1955
1958 class Solution {
1959 public:
1960 static bool hasAlternatingBits(int n);
1961 };
1962 }// namespace binary_number_with_alternating_bits
1963
1966 class Solution {
1967 public:
1968 static int maxConsecutiveAnswers(string answerKey, int k);
1969 };
1970 }// namespace maximize_the_confusion_of_an_exam
1971
1974 struct event {
1975 int time;
1976 bool start;
1979
1980 bool operator<(const event &e) const;
1981 };
1982
1983 class Solution {
1984 public:
1985 static vector<int> busiestServers(int k, vector<int> &arrival, vector<int> &load);
1986 };
1987 }// namespace find_servers_that_handled_most_number_of_requests
1988
1990 namespace self_dividing_numbers {
1991 class Solution {
1992 public:
1993 static vector<int> selfDividingNumbers(int left, int right);
1994 };
1995 }// namespace self_dividing_numbers
1996
1998 namespace array_of_doubled_pairs {
1999 class Solution {
2000 public:
2001 static bool canReorderDoubled(vector<int> &arr);
2002 };
2003 }// namespace array_of_doubled_pairs
2004
2006 namespace strong_password_checker {
2007 class Solution {
2008 public:
2009 static int strongPasswordChecker(const string &password);
2010 };
2011 }// namespace strong_password_checker
2012
2017 class Solution {
2018 public:
2019 static long long numberOfWays(string s);
2020 };
2021 }// namespace number_of_ways_to_select_buildings
2022
2027 class Solution {
2028 public:
2029 static long long sumScores(string s);
2030 };
2031 }// namespace sum_of_scores_of_built_strings
2032
2037 class Solution {
2038 public:
2039 static int convertTime(string current, string correct);
2040 };
2041 }// namespace minimum_number_of_operations_to_convert_time
2042
2047 class Solution {
2048 public:
2049 static vector<vector<int>> findWinners(vector<vector<int>> &matches);
2050 };
2051 }// namespace find_players_with_zero_or_one_losses
2052
2057 class Solution {
2058 public:
2059 static int maximumCandies(vector<int> &candies, long long k);
2060 };
2061 }// namespace maximum_candies_allocated_to_k_children
2062
2066 namespace encrypt_and_decrypt_strings {
2068 array<string, 26> mp;
2069 unordered_map<string, int> count;
2070
2071 public:
2075 Encrypter(vector<char> &keys, vector<string> &values, vector<string> &dictionary);
2080 [[nodiscard]] string encrypt(const string &word1) const;
2085 [[nodiscard]] int decrypt(const string &word2);
2086 };
2087 }// namespace encrypt_and_decrypt_strings
2088
2090 namespace range_sum_query_mutable {
2091 class NumArray {
2092 vector<int> sum;// sum[i] 表示第 i 个块的元素和
2093 int size; // 块的大小
2094 vector<int> &nums;
2095
2096 public:
2098 explicit NumArray(vector<int> &nums);
2100 void update(int index, int val);
2103 [[nodiscard]] int sumRange(int left, int right) const;
2104 };
2105 }// namespace range_sum_query_mutable
2106
2109 class Solution {
2110 public:
2111 static vector<bool> friendRequests(int n, vector<vector<int>> &restrictions, vector<vector<int>> &requests);
2112 };
2113 }// namespace process_restricted_friend_requests
2114
2117 class Solution {
2118 public:
2119 static int countPrimeSetBits(int left, int right);
2120 };
2121 }// namespace prime_number_of_set_bits_in_binary_representation
2122
2124 namespace minimum_height_trees {
2125 class Solution {
2126 public:
2127 static int findLongestNode(int u, vector<int> &parent, vector<vector<int>> &adj);
2128 static vector<int> findMinHeightTrees(int n, vector<vector<int>> &edges);
2129 };
2130 }// namespace minimum_height_trees
2131
2133 namespace rotate_string {
2134 class Solution {
2135 public:
2136 static bool rotateString(string s, const string &goal);
2137 };
2138 }// namespace rotate_string
2139
2142 class Node {
2143 public:
2144 int val{};
2145 vector<Node *> children;
2146 Node() = default;
2147
2148 explicit Node(int _val)
2149 : val(_val){};
2150
2151 Node(int _val, vector<Node *> _children)
2152 : val(_val), children(std::move(std::move(_children))){};
2153 };
2154
2155 class Solution {
2156 public:
2157 static vector<vector<int>> levelOrder(Node *root);
2158 };
2159 }// namespace n_ary_tree_level_order_traversal
2160
2164 namespace reaching_points {
2165 class Solution {
2166 public:
2167 static bool reachingPoints(int sx, int sy, int tx, int ty);
2168 };
2169 }// namespace reaching_points
2170
2175 class Solution {
2176 public:
2177 static int maximumProduct(vector<int> &nums, int k);
2178 };
2179 }// namespace maximum_product_after_k_increments
2180
2185 class Solution {
2186 public:
2187 static long long maximumBeauty(vector<int> &flowers, long long newFlowers, int target, int full, int partial);
2188 };
2189 }// namespace maximum_total_beauty_of_the_gardens
2190
2193 class Solution {
2194 public:
2195 static int countNumbersWithUniqueDigits(int n);
2196 };
2197 }// namespace count_numbers_with_unique_digits
2198
2201 class Solution {
2202 public:
2203 static vector<int> numberOfLines(vector<int> &widths, string s);
2204 };
2205 }// namespace number_of_lines_to_write_string
2206
2208 namespace permutation_in_string {
2209 class Solution {
2210 public:
2211 static bool checkInclusion(const string &s1, string s2);
2212 };
2213 }// namespace permutation_in_string
2214
2216 namespace insert_delete_getrandom_o1 {
2218 unordered_map<int, int> map;
2219 vector<int> nums;
2220 default_random_engine generator;
2221 uniform_int_distribution<int> distribution;
2222
2223 public:
2225 RandomizedSet();
2228 bool insert(int val);
2231 bool remove(int val);
2233 int getRandom();
2234 };
2235 }// namespace insert_delete_getrandom_o1
2236
2239 class Solution {
2240 public:
2241 static int projectionArea(vector<vector<int>> &grid);
2242 };
2243 }// namespace projection_area_of_3d_shapes
2244
2246 namespace design_parking_system {
2248 int big;
2250 int small;
2251
2252 public:
2257 ParkingSystem(int big, int medium, int small);
2261 bool addCar(int carType);
2262 };
2263 }// namespace design_parking_system
2264
2266 namespace range_sum_query_immutable {
2267 class NumArray {
2268 vector<int> pref_sum;
2269
2270 public:
2272 explicit NumArray(vector<int> &nums);
2274 [[nodiscard]] int sumRange(int left, int right) const;
2275 };
2276 }// namespace range_sum_query_immutable
2277
2279 namespace house_robber {
2280 class Solution {
2281 public:
2282 static int rob(vector<int> &nums);
2283 };
2284 }// namespace house_robber
2285
2287 namespace triangle {
2288 class Solution {
2289 public:
2290 static int minimumTotal(vector<vector<int>> &triangle);
2291 };
2292 }// namespace triangle
2293
2296 struct TreeNodeP {
2297 int val;
2302 bool ed;
2303
2304 explicit TreeNodeP(int x)
2305 : val(x), left(nullptr), right(nullptr), parent(nullptr), ed(false) {}
2306 };
2307
2308 class Solution {
2309 public:
2311 static void copy(TreeNode *tn, TreeNodeP *tnp, int low, int high, TreeNodeP **p, TreeNodeP **q);
2312 };
2313 }// namespace lowest_common_ancestor_of_a_binary_search_tree
2314
2316 namespace shuffle_an_array {
2317 class Solution {
2318 vector<int> nums;
2319
2320 public:
2322 explicit Solution(vector<int> &nums);
2324 vector<int> reset();
2326 [[nodiscard]] vector<int> shuffle() const;
2327 };
2328 }// namespace shuffle_an_array
2329
2332 class Solution {
2333 public:
2334 static vector<int> findAnagrams(string s, const string &p);
2335 };
2336 }// namespace find_all_anagrams_in_a_string
2337
2340 class Solution {
2341 public:
2342 static int numSubarrayProductLessThanK(vector<int> &nums, int k);
2343 };
2344 }// namespace subarray_product_less_than_k
2345
2347 namespace minimum_size_subarray_sum {
2348 class Solution {
2349 public:
2350 static int minSubArrayLen(int target, vector<int> &nums);
2351 };
2352 }// namespace minimum_size_subarray_sum
2353
2356 class Solution {
2357 public:
2358 static Node *connect(Node *root);
2359 };
2360 }// namespace populating_next_right_pointers_in_each_node_ii
2361
2363 namespace subtree_of_another_tree {
2364 class Solution {
2365 public:
2366 static bool isSubtree(TreeNode *root, TreeNode *subRoot);
2367 static bool equal(TreeNode *tn1, TreeNode *tn2);
2368 };
2369 }// namespace subtree_of_another_tree
2370
2373 class Solution {
2374 public:
2375 static int shortestPathBinaryMatrix(vector<vector<int>> &grid);
2376 };
2377 }// namespace shortest_path_in_binary_matrix
2378
2380 namespace surrounded_regions {
2381 class Solution {
2382 public:
2383 static void dfs(vector<vector<char>> &board, int x, int y);
2384 static void solve(vector<vector<char>> &board);
2385 };
2386 }// namespace surrounded_regions
2387
2390 class Solution {
2391 public:
2392 static int dfs(vector<vector<int>> &graph, vector<vector<int>> &ans, int cur);
2393 static vector<vector<int>> allPathsSourceTarget(vector<vector<int>> &graph);
2394 };
2395 }// namespace all_paths_from_source_to_target
2396
2398 namespace permutations_ii {
2399 class Solution {
2400 public:
2401 static void dfs(set<vector<int>> &s, const vector<int> &current, vector<int> rest);
2402 static vector<vector<int>> permuteUnique(vector<int> &nums);
2403 };
2404 }// namespace permutations_ii
2405
2407 namespace combination_sum {
2408 class Solution {
2409 public:
2410 static vector<vector<int>> recurse(vector<int> &candidates, int target, int index);
2411 static vector<vector<int>> combinationSum(vector<int> &candidates, int target);
2412 };
2413 }// namespace combination_sum
2414
2416 namespace combination_sum_ii {
2417 class Solution {
2418 public:
2419 static vector<vector<int>> recurse(vector<int> &candidates, int target, int index);
2420 static vector<vector<int>> combinationSum2(vector<int> &candidates, int target);
2421 };
2422 }// namespace combination_sum_ii
2423
2425 namespace house_robber_ii {
2426 class Solution {
2427 public:
2428 static int rob(vector<int> &nums);
2429 };
2430 }// namespace house_robber_ii
2431
2433 namespace jump_game {
2434 class Solution {
2435 public:
2436 static bool canJump(vector<int> &nums);
2437 };
2438 }// namespace jump_game
2439
2441 namespace jump_game_ii {
2442 class Solution {
2443 public:
2444 static int jump(vector<int> &nums);
2445 };
2446 }// namespace jump_game_ii
2447
2449 namespace unique_paths {
2450 class Solution {
2451 public:
2452 static int uniquePaths(int m, int n);
2453 };
2454 }// namespace unique_paths
2455
2458 class Solution {
2459 public:
2460 static string longestPalindrome(string s);
2461 };
2462 }// namespace longest_palindromic_substring
2463
2465 namespace arithmetic_slices {
2466 class Solution {
2467 public:
2468 static int numberOfArithmeticSlices(vector<int> &nums);
2469 };
2470 }// namespace arithmetic_slices
2471
2473 namespace decode_ways {
2474 class Solution {
2475 public:
2476 static int numDecodings(string s);
2477 };
2478 }// namespace decode_ways
2479
2481 namespace word_break {
2482 class Solution {
2483 public:
2484 static void search(const TrieNode *tn, const string &s, int i, vector<bool> &end);
2485 static bool wordBreak(const string &s, vector<string> &wordDict);
2486 };
2487 }// namespace word_break
2488
2491 class Solution {
2492 public:
2493 static int lengthOfLIS(vector<int> &nums);
2494 };
2495 }// namespace longest_increasing_subsequence
2496
2499 class Solution {
2500 public:
2501 static int findNumberOfLIS(vector<int> &nums);
2502 };
2503 }// namespace number_of_longest_increasing_subsequence
2504
2506 namespace longest_common_subsequence {
2507 class Solution {
2508 public:
2509 static int longestCommonSubsequence(string text1, string text2);
2510 };
2511 }// namespace longest_common_subsequence
2512
2515 class Solution {
2516 public:
2517 static int minDistance(const string &word1, const string &word2);
2518 };
2519 }// namespace delete_operation_for_two_strings
2520
2522 namespace edit_distance {
2523 class Solution {
2524 public:
2525 static int minDistance(string word1, string word2);
2526 };
2527 }// namespace edit_distance
2528
2530 namespace coin_change {
2531 class Solution {
2532 public:
2533 static int coinChange(vector<int> &coins, int amount);
2534 };
2535 }// namespace coin_change
2536
2538 namespace integer_break {
2539 class Solution {
2540 public:
2541 static int integerBreak(int n);
2542 };
2543 }// namespace integer_break
2544
2546 namespace max_points_on_a_line {
2547 class Solution {
2548 public:
2549 static int maxPoints(vector<vector<int>> &points);
2550 };
2551 }// namespace max_points_on_a_line
2552
2554 namespace group_anagrams {
2555 class Solution {
2556 public:
2557 static vector<vector<string>> groupAnagrams(vector<string> &strs);
2558 };
2559 }// namespace group_anagrams
2560
2562 namespace sort_colors {
2563 class Solution {
2564 public:
2565 static void qsort(vector<int> &nums, int l, int r);
2566 static void sortColors(vector<int> &nums);
2567 };
2568 }// namespace sort_colors
2569
2571 namespace top_k_frequent_elements {
2572 class Solution {
2573 public:
2574 static vector<int> topKFrequent(vector<int> &nums, int k);
2575 };
2576 }// namespace top_k_frequent_elements
2577
2580 class Solution {
2581 public:
2582 static int findKthLargest(vector<int> &nums, int k);
2583 };
2584 }// namespace kth_largest_element_in_an_array
2585
2587 namespace merge_intervals {
2588 class Solution {
2589 public:
2590 static vector<vector<int>> merge(vector<vector<int>> &intervals);
2591 };
2592 }// namespace merge_intervals
2593
2595 namespace search_a_2d_matrix_ii {
2596 class Solution {
2597 public:
2598 static bool search(const vector<vector<int>> &matrix, int target, int x_start, int x_end, int y_start, int y_end);
2599 static bool searchMatrix(vector<vector<int>> &matrix, int target);
2600 };
2601 }// namespace search_a_2d_matrix_ii
2602
2605 class Codec {
2606 public:
2608 static string serialize(TreeNode *root);
2609
2611 [[nodiscard]] static TreeNode *deserialize(string data);
2612 };
2613 }// namespace serialize_and_deserialize_binary_tree
2614
2616 namespace task_scheduler {
2617 class Solution {
2618 public:
2619 static int leastInterval(vector<char> &tasks, int n);
2620 };
2621 }// namespace task_scheduler
2622
2624 namespace design_hashmap {
2626 static const unsigned SZ = 1021;
2627 array<list<pair<int, int>>, SZ> arr;
2628
2629 public:
2631 MyHashMap();
2632
2634 void put(int key, int value);
2635
2637 int get(int key);
2638
2640 void remove(int key);
2641 };
2642 }// namespace design_hashmap
2643
2645 namespace spiral_matrix_ii {
2646 class Solution {
2647 public:
2648 static vector<vector<int>> generateMatrix(int n);
2649 };
2650 }// namespace spiral_matrix_ii
2651
2653 namespace non_overlapping_intervals {
2654 class Solution {
2655 public:
2656 static int eraseOverlapIntervals(vector<vector<int>> &intervals);
2657 };
2658 }// namespace non_overlapping_intervals
2659
2662 class Solution {
2663 public:
2664 static vector<int> productExceptSelf(vector<int> &nums);
2665 };
2666 }// namespace product_of_array_except_self
2667
2669 namespace subarray_sum_equals_k {
2670 class Solution {
2671 public:
2672 static int subarraySum(vector<int> &nums, int k);
2673 };
2674 }// namespace subarray_sum_equals_k
2675
2677 namespace partition_labels {
2678 class Solution {
2679 public:
2680 static vector<int> partitionLabels(string s);
2681 };
2682 }// namespace partition_labels
2683
2685 namespace repeated_dna_sequences {
2686 class Solution {
2687 public:
2688 static vector<string> findRepeatedDnaSequences(string s);
2689 };
2690 }// namespace repeated_dna_sequences
2691
2693 namespace design_linked_list {
2697
2698 public:
2700 MyLinkedList();
2702 [[nodiscard]] int get(int index) const;
2704 void addAtHead(int val);
2706 void addAtTail(int val);
2712 void addAtIndex(int index, int val);
2714 void deleteAtIndex(int index);
2715 };
2716 }// namespace design_linked_list
2717
2719 namespace delete_node_in_a_bst {
2720 class Solution {
2722
2723 public:
2726 void remove(TreeNode *node);
2727 TreeNode *deleteNode(TreeNode *root, int key);
2728 };
2729 }// namespace delete_node_in_a_bst
2730
2733 class Solution {
2734 public:
2735 static unsigned missing(vector<int> &nums, int i);
2736 static int missingElement(vector<int> &nums, int k);
2737 };
2738 }// namespace missing_element_in_sorted_array
2739
2741 namespace find_a_peak_element_ii {
2742 class Solution {
2743 public:
2744 static int get(vector<vector<int>> &mat, int i, int j);
2745 static vector<int> findPeakGridLR(vector<vector<int>> &mat, int l, int r);
2746 static vector<int> findPeakGrid(vector<vector<int>> &mat);
2747 };
2748 }// namespace find_a_peak_element_ii
2749
2751 namespace divide_chocolate {
2752 class Solution {
2753 public:
2754 static int count(vector<int> &sweetness, int x);
2755 static int maximizeSweetness(vector<int> &sweetness, int k);
2756 };
2757 }// namespace divide_chocolate
2758
2761 class Solution {
2762 public:
2763 static vector<int> shortestDistanceColor(vector<int> &colors, vector<vector<int>> &queries);
2764 };
2765 }// namespace shortest_distance_to_target_color
2766
2768 namespace meeting_scheduler {
2769 class Solution {
2770 public:
2771 static pair<int, int> merge(const vector<int> &vec1, const vector<int> &vec2);
2772 static vector<int> minAvailableDuration(vector<vector<int>> &slots1, vector<vector<int>> &slots2, int duration);
2773 };
2774 }// namespace meeting_scheduler
2775
2777 namespace find_the_duplicate_number {
2778 class Solution {
2779 public:
2780 static int countInRange(vector<int> &nums, int l, int r);
2781 static int findDuplicate(vector<int> &nums);
2782 };
2783 }// namespace find_the_duplicate_number
2784
2786 namespace trapping_rain_water {
2787 class Solution {
2788 public:
2789 static int trap(vector<int> &height);
2790 };
2791 }// namespace trapping_rain_water
2792
2795 class Solution {
2796 public:
2797 static vector<vector<int>> findRLEArray(vector<vector<int>> &encoded1, vector<vector<int>> &encoded2);
2798 };
2799 }// namespace product_of_two_run_length_encoded_arrays
2800
2803 class Solution {
2804 public:
2805 static int getMinUniqueCharCnt(const string &s, int len);
2806 static int lengthOfLongestSubstringTwoDistinct(const string &s);
2807 };
2808 }// namespace longest_substring_with_at_most_two_distinct_characters
2809
2812 class Solution {
2813 public:
2814 static int lengthOfLongestSubstringKDistinct(const string &s, int k);
2815 };
2816 }// namespace longest_substring_with_at_most_k_distinct_characters
2817
2819 namespace max_consecutive_ones_iii {
2820 class Solution {
2821 public:
2822 static int cntMinFlip(vector<int> &nums, int len);
2823 static int longestOnes(vector<int> &nums, int k);
2824 };
2825 }// namespace max_consecutive_ones_iii
2826
2828 namespace sliding_window_maximum {
2829 class Solution {
2830 public:
2831 static vector<int> maxSlidingWindow(vector<int> &nums, int k);
2832 };
2833 }// namespace sliding_window_maximum
2834
2836 namespace minimum_window_substring {
2837 class Solution {
2838 public:
2839 static bool valid(unordered_map<char, int> &ums, const unordered_map<char, int> &umt);
2840 static string minWindow(string s, const string &t);
2841 };
2842 }// namespace minimum_window_substring
2843
2845 namespace walls_and_gates {
2846 class Solution {
2847 public:
2848 static void wallsAndGates(vector<vector<int>> &rooms);
2849 };
2850 }// namespace walls_and_gates
2851
2853 namespace pacific_atlantic_waterflow {
2854 struct myhash {
2855 size_t operator()(const pair<int, int> &p) const;
2856 };
2857
2858 struct myeq {
2859 bool operator()(const pair<int, int> &p1, const pair<int, int> &p2) const;
2860 };
2861
2862 class Solution {
2863 public:
2864 static vector<vector<int>> pacificAtlantic(vector<vector<int>> &heights);
2865 };
2866 }// namespace pacific_atlantic_waterflow
2867
2869 namespace find_all_the_lonely_nodes {
2870 class Solution {
2871 public:
2872 static vector<int> getLonelyNodes(TreeNode *root);
2873 };
2874 }// namespace find_all_the_lonely_nodes
2875
2877 namespace kill_process {
2878 struct Node {
2879 int val;
2880 unordered_set<Node *> children;
2881
2882 explicit Node(int val)
2883 : val(val) {}
2884 };
2885
2886 class Solution {
2887 public:
2888 static vector<int> killProcess(vector<int> &pid, vector<int> &ppid, int kill);
2889 };
2890 }// namespace kill_process
2891
2894 struct Node {
2895 int val;
2896 unordered_set<Node *> siblings;
2897
2898 explicit Node(int val)
2899 : val(val) {}
2900 };
2901
2902 class Solution {
2903 public:
2904 static vector<int> distanceK(TreeNode *root, TreeNode *target, int k);
2905 };
2906 }// namespace all_nodes_distance_k_in_binary_tree
2907
2909 namespace open_the_lock {
2910 class Solution {
2911 public:
2912 static int openLock(vector<string> &deadends, const string &target);
2913 };
2914 }// namespace open_the_lock
2915
2918 class Solution {
2919 public:
2920 static void dfs(int &edge_cnt, int &node_cnt, unordered_set<int> &vis, int node, vector<unordered_set<int>> &g);
2921 static int makeConnected(int n, vector<vector<int>> &connections);
2922 };
2923 }// namespace number_of_operations_to_make_network_connected
2924
2927 struct Node {
2928 int x;
2929 int y;
2930 unordered_map<Node *, int> siblings;
2931
2932 Node(int x, int y)
2933 : x(x), y(y) {}
2934 };
2935
2936 struct mycmp {
2937 bool operator()(const pair<int, Node *> &p1, const pair<int, Node *> &p2) const;
2938 };
2939
2940 class Solution {
2941 public:
2942 static int minCost(vector<vector<int>> &grid);
2943 };
2944 }// namespace minimum_cost_to_make_at_least_one_valid_path_in_a_grid
2945
2948 class Solution {
2949 public:
2950 static void tarjan(int prev, int &step, vector<int> &dfn, int node, vector<unordered_set<int>> &g, vector<int> &low, vector<vector<int>> &ans);
2951 static vector<vector<int>> criticalConnections(int n, vector<vector<int>> &connections);
2952 };
2953 }// namespace critical_connections_in_a_network
2954
2956 namespace factor_combinations {
2957 class Solution {
2958 public:
2959 static vector<vector<int>> getFactorsWithMin(int n, int minimum);
2960 static vector<vector<int>> getFactors(int n);
2961 };
2962 }// namespace factor_combinations
2963
2965 namespace decode_string {
2966 class Solution {
2967 public:
2968 static string decodeString(string s);
2969 };
2970 }// namespace decode_string
2971
2973 namespace n_queens {
2974 class Solution {
2975 static void dfs(const vector<vector<bool>> &board, int line, int n, vector<vector<string>> &ans);
2976 static bool valid(const vector<vector<bool>> &board, int n, int x, int y);
2977 static vector<string> toStringVec(const vector<vector<bool>> &board);
2978
2979 public:
2980 static vector<vector<string>> solveNQueens(int n);
2981 };
2982 }// namespace n_queens
2983
2985 namespace sudoku_solver {
2986 class Solution {
2987 static bool dfs(const vector<vector<char>> &board, vector<vector<char>> &ans);
2988 static bool valid(const vector<vector<char>> &board, int x, int y, char num);
2989
2990 public:
2991 static void solveSudoku(vector<vector<char>> &board);
2992 };
2993 }// namespace sudoku_solver
2994
2996 namespace regular_expression_matching {
2997 class Solution {
2998 public:
2999 static bool dfs(const string &s, const string &p, int si, int pi);
3000 static bool isMatch(const string &s, const string &p);
3001 };
3002 }// namespace regular_expression_matching
3003
3006 class Solution {
3007 public:
3008 static vector<int> diffWaysToCompute(const string &expression);
3009 static vector<int> eval(const string &expr, int start, int end);
3010 };
3011 }// namespace different_ways_to_add_parentheses
3012
3014 namespace remove_invalid_parentheses {
3015 class Solution {
3016 public:
3017 static bool isValid(const string &str);
3018 static vector<string> removeInvalidParentheses(const string &s);
3019 };
3020 }// namespace remove_invalid_parentheses
3021
3023 namespace median_of_two_sorted_arrays {
3024 class Solution {
3025 public:
3026 static double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2);
3027 };
3028 }// namespace median_of_two_sorted_arrays
3029
3032 class Solution {
3033 private:
3034 vector<int> c;
3035 vector<int> a;
3036 void Init(int length);
3037 static int LowBit(int x);
3038 void Update(int pos);
3039 [[nodiscard]] int Query(int pos) const;
3040 void Discretization(vector<int> &nums);
3041 int getId(int x);
3042
3043 public:
3044 vector<int> countSmaller(vector<int> &nums);
3045 };
3046 }// namespace count_of_smaller_numbers_after_self
3047
3050 class Solution {
3051 public:
3052 static int maxProfit(vector<int> &prices);
3053 };
3054 }// namespace best_time_to_buy_and_sell_stock_with_cooldown
3055
3058 class Solution {
3059 public:
3060 static int maxProfit(vector<int> &prices, int fee);
3061 };
3062 }// namespace best_time_to_buy_and_sell_stock_with_transaction_fee
3063
3065 namespace split_array_largest_sum {
3066 class Solution {
3067 public:
3068 static int get_m(const vector<int> &nums, int msum);
3069 static int splitArray(vector<int> &nums, int m);
3070 };
3071 }// namespace split_array_largest_sum
3072
3074 namespace house_robber_iii {
3075 struct myhash {
3076 size_t operator()(const pair<TreeNode *, bool> &p) const;
3077 };
3078
3079 struct myeq {
3080 bool operator()(const pair<TreeNode *, bool> &p1, const pair<TreeNode *, bool> &p2) const;
3081 };
3082
3083 class Solution {
3084 unordered_map<pair<TreeNode *, bool>, int, myhash, myeq> um;
3085
3086 public:
3087 int dfs(bool steal, TreeNode *node);
3088 int rob(TreeNode *root);
3089 };
3090 }// namespace house_robber_iii
3091
3093 namespace maximal_square {
3094 class Solution {
3095 public:
3096 static int maximalSquare(vector<vector<char>> &matrix);
3097 };
3098 }// namespace maximal_square
3099
3101 namespace maximal_rectangle {
3102 class Solution {
3103 public:
3104 static int maximalRectangle(vector<vector<char>> &matrix);
3105 };
3106 }// namespace maximal_rectangle
3107
3109 namespace predict_the_winner {
3110 class Solution {
3111 public:
3112 static bool PredictTheWinner(vector<int> &nums);
3113 };
3114 }// namespace predict_the_winner
3115
3117 namespace palindrome_partitioning {
3118 class Solution {
3119 public:
3120 static bool is_palindromic(const string &s, int start, int end);
3121 static void dfs(const vector<string> &current, const string &s, vector<vector<string>> &ans, int start, int cursor);
3122 static vector<vector<string>> partition(const string &s);
3123 };
3124 }// namespace palindrome_partitioning
3125
3127 namespace palindrome_partitioning_ii {
3128 class Solution {
3129 public:
3130 static int minCut(string s);
3131 };
3132 }// namespace palindrome_partitioning_ii
3133
3135 namespace partition_equal_subset_sum {
3136 class Solution {
3137 public:
3138 static bool canPartition(vector<int> &nums);
3139 };
3140 }// namespace partition_equal_subset_sum
3141
3143 namespace minimum_cost_for_tickets {
3144 class Solution {
3145 public:
3146 static int mincostTickets(vector<int> &days, vector<int> &costs);
3147 };
3148 }// namespace minimum_cost_for_tickets
3149
3152 class Solution {
3153 public:
3154 static int maxProfit(vector<int> &prices);
3155 };
3156 }// namespace best_time_to_buy_and_sell_stock_iii
3157
3159 namespace dungeon_game {
3160 class Solution {
3161 public:
3162 static int calculateMinimumHP(vector<vector<int>> &dungeon);
3163 };
3164 }// namespace dungeon_game
3165
3167 namespace course_schedule {
3168 class Solution {
3169 public:
3170 static bool canFinish(int numCourses, vector<vector<int>> &prerequisites);
3171 };
3172 }// namespace course_schedule
3173
3175 namespace course_schedule_ii {
3176 class Solution {
3177 public:
3178 static vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites);
3179 };
3180 }// namespace course_schedule_ii
3181
3184 class Solution {
3185 public:
3186 int rows;
3188 static constexpr int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
3189 int longestIncreasingPath(vector<vector<int>> &matrix);
3190 };
3191 }// namespace longest_increasing_path_in_a_matrix
3192
3194 namespace parallel_courses {
3195 struct node {
3196 int n;
3197 int out;
3198 int len = 1;
3199 unordered_set<node *> pred;
3200
3201 node(int n, int out)
3202 : n(n), out(out) {}
3203 };
3204
3205 class Solution {
3206 public:
3207 static int minimumSemesters(int n, vector<vector<int>> &relations);
3208 };
3209 }// namespace parallel_courses
3210
3212 namespace alien_dictionary {
3213 class Solution {
3214 public:
3215 static string alienOrder(vector<string> &words);
3216 };
3217 }// namespace alien_dictionary
3218
3220 namespace single_number_iii {
3221 class Solution {
3222 public:
3223 static vector<int> singleNumber(vector<int> &nums);
3224 };
3225 }// namespace single_number_iii
3226
3229 constexpr char EMPTY = '.';
3230 constexpr char WALL = '#';
3231 constexpr char START = '@';
3232
3233 struct frame {
3234 int x;
3235 int y;
3237 int step = 0;
3238 unordered_set<char> keys;
3239
3240 frame(int x, int y, int lock_left)
3241 : x(x), y(y), lock_left(lock_left) {}
3242
3243 bool operator<(const frame &f) const;
3244 [[nodiscard]] unsigned get_mask() const;
3245 };
3246
3247 class Solution {
3248 public:
3249 static int shortestPathAllKeys(vector<string> &grid);
3250 };
3251 }// namespace shortest_path_to_get_all_keys
3252
3255 class Solution {
3256 public:
3257 static int minKBitFlips(vector<int> &nums, int k);
3258 };
3259 }// namespace minimum_number_of_k_consecutive_bit_flips
3260
3262 namespace design_underground_system {
3264 unordered_map<string, unordered_map<string, vector<int>>> um;
3265 unordered_map<int, pair<string, int>> records;
3266
3267 public:
3271 void checkIn(int id, const string &stationName, int t);
3273 void checkOut(int id, const string &stationName, int t);
3278 double getAverageTime(const string &startStation, const string &endStation);
3279 };
3280 }// namespace design_underground_system
3281
3283 namespace lru_cache {
3284 class LRUCache {
3286 list<int> keys;
3287 unordered_map<int, int> um;
3288
3289 public:
3291 LRUCache(int capacity);
3293 int get(int key);
3295 void put(int key, int value);
3296 };
3297 }// namespace lru_cache
3298
3300 namespace time_based_key_value_store {
3301 class TimeMap {
3302 unordered_map<string, map<int, string, greater<int>>> um;
3303
3304 public:
3306 TimeMap() = default;
3308 void set(const string &key, string value, int timestamp);
3310 // 如果有多个这样的值,则返回对应最大的 timestamp_prev 的那个值。
3311 // 如果没有值,则返回空字符串("")。
3312 string get(const string &key, int timestamp);
3313 };
3314 }// namespace time_based_key_value_store
3315
3317 namespace range_module {
3318 class Chtholly {
3319 using type = bool;
3320
3321 struct Node {
3322 unsigned l{}, r{};
3324
3325 Node(unsigned l, unsigned r = 0, type data = false)
3326 : l(l), r(r), data(data) {}
3327
3328 bool operator<(const Node &rhs) const { return l < rhs.l; }
3329 };
3330
3331 public:
3332 set<Node> s;
3333
3334 auto split(unsigned pos) {
3335 auto it = s.lower_bound({pos});
3336 if(it != s.end() && it->l == pos)
3337 return it;
3338 auto [l, r, d]{*--it};
3339 s.erase(it);
3340 s.emplace(l, pos - 1, d);
3341 return s.emplace(pos, r, d).first;
3342 }
3343
3344 void assign(unsigned l, unsigned r, type val = false) {
3345 const auto it = split(r + 1);
3346 s.erase(split(l), it);
3347 s.emplace(l, r, val);
3348 }
3349
3350 bool check(unsigned l, unsigned r) {
3351 const auto it = split(r + 1);
3352 return std::all_of(split(l), it, [](auto &&n) { return n.data; });
3353 }
3354 };
3355
3357 Chtholly tree{{{1, 100000000}}};
3358
3359 public:
3361 RangeModule() = default;
3363 void addRange(int left, int right);
3365 bool queryRange(int left, int right);
3367 void removeRange(int left, int right);
3368 };
3369 }// namespace range_module
3370
3372 namespace lfu_cache {
3373 class LFUCache {
3374 unordered_map<int, int> um;
3375 unordered_map<int, int> cnt;
3376 map<int, list<int>> tnc;
3378
3379 public:
3383
3384 int get(int key);
3386 void put(int key, int value);
3387 };
3388 }// namespace lfu_cache
3389
3391 namespace leetcode454_4sum_ii {
3392 class Solution {
3393 vector<unordered_map<int, int>> mem;
3394 vector<unordered_map<int, int>> vec;
3395
3396 public:
3397 int sumCount(int sum, int i);
3398 int fourSumCount(vector<int> &nums1, vector<int> &nums2, vector<int> &nums3, vector<int> &nums4);
3399 };
3400 }// namespace leetcode454_4sum_ii
3401
3404 class Solution {
3405 public:
3406 static int maxSubArrayLen(vector<int> &nums, int k);
3407 };
3408 }// namespace maximum_size_subarray_sum_equals_k
3409
3412 class Solution {
3413 public:
3414 static int minSwaps(vector<int> &data);
3415 };
3416 }// namespace minimum_swaps_to_group_all_1s_together
3417}// namespace leetcode
3418
3419#endif//PROBLEMSCPP_LEETCODE_H
LeetCode 1185. 一周中的第几天
LeetCode 913. 猫和老鼠
LeetCode 71. 简化路径
LeetCode 1614. 括号的最大嵌套深度
LeetCode 89. 格雷编码
LeetCode 5976. 检查是否每一行每一列都包含全部整数
LeetCode 5977. 最少交换次数来组合所有的 1 II
LeetCode 5978. 统计追加字母可以获得的单词数
LeetCode 1629. 按键持续时间最长的键
LeetCode 306. 累加数
LeetCode 2075. 解码斜向换位密码
LeetCode 1036. 逃离大迷宫
LeetCode 334. 递增的三元子序列
LeetCode 747. 至少是其他数字两倍的最大数
LeetCode 373. 查找和最小的K对数字
LeetCode 46. 全排列
LeetCode 1716. 计算力扣银行的钱
LeetCode 382. 链表随机节点
LeetCode 5194. 得到目标值的最少行动次数
LeetCode 5982. 解决智力问题
LeetCode 5983. 同时运行 N 台电脑的最长时间
LeetCode 1220. 统计元音字母序列的数目
LeetCode 539. 最小时间差
LeetCode 219. 存在重复元素 II
LeetCode 2029. 石子游戏 IX
LeetCode 1345. 跳跃游戏 IV
LeetCode 1332. 删除回文子序列
剑指 Offer II 063. 替换单词
LeetCode 5971. 打折购买糖果的最小开销
LeetCode 5972. 统计隐藏数组数目
LeetCode 5973. 价格范围内最高排名的 K 样物品
LeetCode 5974. 分隔长廊的方案数
LeetCode 5991. 按符号重排数组
LeetCode 5990. 找出数组中的所有孤独数字
LeetCode 5992. 基于陈述统计最多好人数
LeetCode 2034. 股票价格波动
LeetCode 2045. 到达目的地的第二短时间
LeetCode 1688. 比赛中的配对次数
LeetCode 2013. 检测正方形
LeetCode 2047. 句子中的有效单词数
LeetCode 1996. 游戏中弱角色的数量
LeetCode 面试题 16.18. 模式匹配
LeetCode 1765. 地图中的最高点
LeetCode 884. 两句话中的不常见单词
LeetCode 5993. 将找到的值乘以 2
LeetCode 5981. 分组得分最高的所有下标
LeetCode 5994. 查找给定哈希值的子串
LeetCode 5995. 字符串分组
LeetCode 1342. 将数字变成 0 的操作次数
LeetCode 1763. 最长的美好子字符串
LeetCode 2000. 反转单词前缀
LeetCode 1414. 和为 K 的最少斐波那契数字数目
LeetCode 1725. 可以形成最大正方形的矩形数目
LeetCode 1219. Path with Maximum Gold
LeetCode 5984. 拆分数位后四位数字的最小和
LeetCode 5985. 根据给定数字划分数组
LeetCode 5986. 设置时间的最少代价
LeetCode 5987. 删除元素后和的最小差值
LeetCode 1748. 唯一元素的和
LeetCode 6000. 对奇偶下标分别排序
LeetCode 6001. 重排数字的最小值
LeetCode 6002. 设计位集
LeetCode 1405. Longest Happy String
LeetCode 1001. Grid Illumination
LeetCode 2006. Count Number of Pairs With Absolute Difference K
LeetCode 1447. Simplified Fractions
LeetCode 1984. Minimum Difference Between Highest and Lowest of K Scores
LeetCode 1020. Number of Enclaves
LeetCode 1189. “气球” 的最大数量
LeetCode 777. 在LR字符串中交换相邻字符
LeetCode 6004. 得到 0 的操作数
LeetCode 6005. 使数组变成交替数组的最少操作数
LeetCode 6006. 拿出最少数目的魔法豆
LeetCode 6007. 数组的最大与和
LeetCode 540. Single Element in a Sorted Array
LeetCode 1380. Lucky Numbers in a Matrix
LeetCode 1719. Number Of Ways To Reconstruct A Tree
LeetCode 1791. Find Center of Star Graph
LeetCode 688. Knight Probability in Chessboard
LeetCode 969. Pancake Sorting
LeetCode 5996. 统计数组中相等且可以被整除的数对
LeetCode 5997. 找到和为给定整数的三个连续整数
LeetCode 5998. 拆分成最多数目的偶整数之和
LeetCode 5999. 统计数组中好三元组数目
LeetCode 6012. 统计各位数字之和为偶数的整数个数
LeetCode 6013. 合并零之间的节点
LeetCode 6014. 构造限制重复的字符串
LeetCode 6015. 统计可以被 K 整除的下标对数目
LeetCode 717. 1比特与2比特字符
LeetCode 845. 数组中的最长山脉
LeetCode 838. 推多米诺
LeetCode 1994. 好子集的数目
LeetCode 917. Reverse Only Letters
LeetCode 1706. Where Will the Ball Fall
LeetCode 537. Complex Number Multiplication
LeetCode 2016. Maximum Difference Between Increasing Elements
LeetCode 553. Optimal Division
LeetCode 6008. 统计包含给定前缀的字符串
LeetCode 6009. 使两字符串互为字母异位词的最少步骤数
LeetCode 6010. 完成旅途的最少时间
LeetCode 6011. 完成比赛的最少时间
LeetCode 1601. Maximum Number of Achievable Transfer Requests
LeetCode 6. ZigZag Conversion
LeetCode 564. Find the Closest Palindrome
LeetCode 258. Add Digits
LeetCode 2104. Sum of Subarray Ranges
LeetCode 521. Longest Uncommon Subsequence I
LeetCode 6024. 数组中紧跟 key 之后出现最频繁的数字
LeetCode 5217. 将杂乱无章的数字排序
LeetCode 5300. 有向无环图中一个节点的所有祖先
LeetCode 5237. 得到回文串的最少操作次数
LeetCode 6016. Excel 表中某个范围内的单元格
LeetCode 6017. 向数组中追加 K 个整数
LeetCode 6018. 根据描述创建二叉树
LeetCode 6019. 替换数组中的非互质数
LeetCode 2100. Find Good Days to Rob the Bank
LeetCode 504. Base 7
LeetCode 2055. Plates Between Candles
LeetCode 798. Smallest Rotation with Highest Score
LeetCode 589. N-ary Tree Preorder Traversal
LeetCode 2049. Count Nodes With the Highest Score
LeetCode 590. N-ary Tree Postorder Traversal
LeetCode 695. Max Area of Island
LeetCode 6031. 找出数组中的所有 K 近邻下标
LeetCode 5203. 统计可以提取的工件
LeetCode 5227. K 次操作后最大化顶端元素
LeetCode 6032. 得到要求路径的最小带权子图
LeetCode 393. UTF-8 Validation
LeetCode 599. Minimum Index Sum of Two Lists
LeetCode 2044. Count Number of Maximum Bitwise-OR Subsets
LeetCode 432. All O`one Data Structure
LeetCode 720. Longest Word in Dictionary
LeetCode 2043. Simple Bank System
LeetCode 606. Construct String from Binary Tree
LeetCode 6021. Maximize Number of Subsequences in a String
LeetCode 6022. Minimum Operations to Halve Array Sum
LeetCode 6023. Minimum White Tiles After Covering With Carpets
LeetCode 6027. Count Hills and Valleys in an Array
LeetCode 6028. Count Collisions on a Road
LeetCode 6029. Maximum Points in an Archery Competition
LeetCode 2039. The Time When the Network Becomes Idle
LeetCode 653. Two Sum IV - Input is a BST
Remove Colored Pieces if Both Neighbors are the Same Color
K-th Smallest in Lexicographical Order
unsigned long long qmi(unsigned long long m, unsigned long long k)
Binary Number with Alternating Bits
Maximize the Confusion of an Exam
Find Servers That Handled Most Number of Requests
Minimum Number of Operations to Convert Time
Find Players With Zero or One Losses
Maximum Candies Allocated to K Children
Process Restricted Friend Requests
Prime Number of Set Bits in Binary Representation
Lowest Common Ancestor of a Binary Search Tree
Populating Next Right Pointers in Each Node II
Number of Longest Increasing Subsequence
Serialize and Deserialize Binary Tree
与目标颜色间的最短距离
太平洋大西洋水流问题
二叉树中所有距离为 K 的结点
使网格图至少有一条有效路径的最小代价
查找集群内的「关键连接」
为运算表达式设计优先级
寻找两个正序数组的中位数
计算右侧小于当前元素的个数
只出现一次的数字 III
获取所有钥匙的最短路径
和等于 k 的最长子数组长度
最少交换次数来组合所有的 1
TreeNode(int x, TreeNode *left, TreeNode *right)
bool operator==(const TreeNode &) const
bool operator!=(const TreeNode &) const
ListNode(int x, ListNode *next)
Node(int _val, Node *_left, Node *_right, Node *_next)
static vector< string > findAllConcatenatedWordsInADict(vector< string > &)
bool dfs(TrieNode *, const string &, int, bool) const
static int titleToNumber(const string &columnTitle)
static string convertToTitle(int columnNumber)
int majorityElement(vector< int > &nums)
static bool isNStraightHand(vector< int > &hand, int groupSize)
static TreeNode * convertBST(TreeNode *root)
static FriendTreeNode * copy(TreeNode *)
static vector< vector< int > > construct2DArray(vector< int > &original, int m, int n)
static bool asteroidsDestroyed(int mass, vector< int > &asteroids)
static string dayOfTheWeek(int day, int month, int year)
int getResult(int mouse, int cat, int turns)
int dp[MAXN][MAXN][MAXN *2]
int catMouseGame(vector< vector< int > > &graph)
void getNextResult(int mouse, int cat, int turns)
vector< vector< int > > graph
static string simplifyPath(const string &path)
static vector< int > grayCode(int n)
static int wordCount(vector< string > &startWords, vector< string > &targetWords)
static char slowestKey(vector< int > &releaseTimes, string keysPressed)
static bool dfs(unsigned long long n1, unsigned long long n2, const char *, unsigned short length, unsigned short current)
static bool isAdditiveNumber(string num)
static unsigned long long str2ui(const char *, unsigned short start, unsigned short length)
将字符串的一个子串转换为整数
static bool equal(string, const char *, unsigned short start, unsigned short length)
判断一个字符串与另一个字符串的子串是否相等
static string decodeCiphertext(string encodedText, int rows)
static string rtrim(string &s)
去除字符串右边的空白符 https://blog.csdn.net/tiandyoin/article/details/81508445
bool operator==(const point &p) const
bool operator<(const point &p) const
point(unsigned int x, unsigned int y, int distance, point *target)
size_t operator()(const point &p) const
static bool isEscapePossible(vector< vector< int > > &blocked, vector< int > &source, vector< int > &target)
static unsigned int search(unordered_set< point, point_hash > &block_set, point *source, point *target, unsigned int limit)
在迷宫中以source为起点搜索
static bool increasingTriplet(vector< int > &nums)
static vector< vector< int > > kSmallestPairs(vector< int > &nums1, vector< int > &nums2, int k)
static vector< vector< int > > permute(vector< int > &nums)
static vector< string > divideString(const string &s, int k, char fill)
static long long mostPoints(vector< vector< int > > &questions)
static long long maxRunTime(int n, vector< int > &batteries)
static int findMinDifference(vector< string > &timePoints)
static bool containsNearbyDuplicate(vector< int > &nums, int k)
static bool stoneGameIX(vector< int > &stones)
static int minJumps(vector< int > &arr)
void insert(const string &str)
string get_prefix(string root, const string &str) const
static string replaceWords(vector< string > &dictionary, const string &sentence)
static int numberOfArrays(vector< int > &differences, int lower, int upper)
item(int distance, int price, int row, int col)
static vector< vector< int > > highestRankedKItems(vector< vector< int > > &grid, vector< int > &pricing, vector< int > &start, int k)
static vector< int > rearrangeArray(vector< int > &nums)
static vector< int > findLonely(vector< int > &nums)
static int maximumGood(vector< vector< int > > &statements)
static pair< int, unordered_map< int, bool > > dfs(vector< vector< int > > &statements, unordered_map< int, bool > um, queue< msg > que)
static int secondMinimum(int n, vector< vector< int > > &edges, int time, int change)
multiset< pair< int, int > > ms
int count(vector< int > point) const
static int numberOfWeakCharacters(vector< vector< int > > &properties)
static bool patternMatching(const string &pattern, const string &value)
static vector< vector< int > > highestPeak(vector< vector< int > > &isWater)
static vector< string > uncommonFromSentences(const string &s1, const string &s2)
static int findFinalValue(vector< int > &nums, int original)
static string subStrHash(string s, int power, int modulo, int k, int hashValue)
unordered_map< unsigned int, unsigned int > rank
unordered_map< unsigned int, unsigned int > size
unordered_map< unsigned int, unsigned int > parent
static unsigned int compress(const string &word)
vector< int > groupStrings(vector< string > &words)
void to_union(unsigned int x1, unsigned int x2)
unsigned int find(unsigned int x)
static string longestNiceSubstring(const string &s)
static pair< int, int > dfs(string s, int start, int end)
static string reversePrefix(string word, char ch)
static int find_min(set< int, greater<> > &fibb, int k, set< int, greater<> >::iterator begin)
static int countGoodRectangles(vector< vector< int > > &rectangles)
static int get_sum(int current, int x, int y, int m, int n, vector< vector< int > > &grid, bool **occupied)
static int getMaximumGold(vector< vector< int > > &grid)
static vector< int > pivotArray(vector< int > &nums, int pivot)
static int get_cost(int startAt, int moveCost, int pushCost, const int num[4])
static int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds)
static int sumOfUnique(vector< int > &nums)
static vector< int > sortEvenOdd(vector< int > &nums)
Bitset(int size)
用 size 个位初始化 Bitset ,所有位都是 0 。
string toString() const
返回 Bitset 的当前组成情况。注意,在结果字符串中,第 i 个下标处的字符应该与 Bitset 中的第 i 位一致。
bool one() const
检查 Bitset 中 是否 至少一位 的值是 1 。如果满足此条件,返回 true ;否则,返回 false 。
void fix(int idx) const
将下标为 idx 的位上的值更新为 1 。如果值已经是 1 ,则不会发生任何改变。
bool all() const
检查 Bitset 中 每一位 的值是否都是 1 。如果满足此条件,返回 true ;否则,返回 false 。
void flip()
翻转 Bitset 中每一位上的值。换句话说,所有值为 0 的位将会变成 1 ,反之亦然。
int count() const
返回 Bitset 中值为 1 的位的 总数 。
void unfix(int idx) const
将下标为 idx 的位上的值更新为 0 。如果值已经是 0 ,则不会发生任何改变。
static int * get_p(char ch, int *a, int *b, int *c)
static void sort(char ch[3], int a, int b, int c)
static string longestDiverseString(int a, int b, int c)
unsigned long long operator()(const pair< int, int > &) const
static vector< int > gridIllumination(int n, vector< vector< int > > &lamps, vector< vector< int > > &queries)
static vector< string > simplifiedFractions(int n)
static int numEnclaves(vector< vector< int > > &grid)
static int maxNumberOfBalloons(const string &text)
static bool canTransform(const string &start, const string &end)
static int maximumANDSum(vector< int > &nums, int numSlots)
static vector< int > luckyNumbers(vector< vector< int > > &matrix)
static int checkWays(vector< vector< int > > &pairs)
static int findCenter(vector< vector< int > > &edges)
bool operator()(const status &, const status &) const
unordered_map< status, double, status_hash, status_equal > um
double knightProbability(int n, int k, int row, int column)
static vector< int > pancakeSort(vector< int > &arr)
static vector< long long > maximumEvenSplit(long long finalSum)
static long long goodTriplets(vector< int > &nums1, vector< int > &nums2)
static string repeatLimitedString(const string &s, int repeatLimit)
static long long coutPairs(vector< int > &nums, int k)
static int longestMountain(vector< int > &arr)
static string pushDominoes(string dominoes)
static int numberOfGoodSubsets(vector< int > &nums)
static constexpr array< int, 10 > primes
static vector< int > findBall(vector< vector< int > > &grid)
static string complexNumberMultiply(const string &num1, const string &num2)
static string optimalDivision(vector< int > &nums)
static int prefixCount(vector< string > &words, string pref)
static long long minimumTime(vector< int > &time, int totalTrips)
static int minimumFinishTime(vector< vector< int > > &tires, int changeTime, int numLaps)
static int maximumRequests(int n, vector< vector< int > > &requests)
static string convert(string s, int numRows)
static string nearestPalindromic(const string &n)
static long long subArrayRanges(vector< int > &nums)
static int findLUSlength(const string &a, const string &b)
bool operator()(const tuple< int, int, int > &s1, const tuple< int, int, int > &s2) const
static vector< int > sortJumbled(vector< int > &mapping, vector< int > &nums)
vector< vector< int > > getAncestors(int n, vector< vector< int > > &edges)
static vector< string > cellsInRange(const string &s)
static long long minimalKSum(vector< int > &nums, int k)
static TreeNode * createBinaryTree(vector< vector< int > > &descriptions)
static vector< int > replaceNonCoprimes(vector< int > &nums)
static vector< int > goodDaysToRobBank(vector< int > &security, int time)
static string convertToBase7(int num)
static vector< int > platesBetweenCandles(string s, vector< vector< int > > &queries)
Node(int _val, vector< Node * > _children)
static int countHighestScoreNodes(vector< int > &parents)
Node(int _val, vector< Node * > _children)
unordered_map< pair< int, int >, int, function< unsigned int(const pair< int, int > &)> > size
unordered_map< pair< int, int >, int, function< unsigned int(const pair< int, int > &)> > rank
bool same(pair< int, int > a, pair< int, int > b)
void merge(pair< int, int > a, pair< int, int > b)
bool contains(pair< int, int > p) const
unordered_map< pair< int, int >, pair< int, int >, function< unsigned int(const pair< int, int > &)> > parent
pair< int, int > find(pair< int, int > val)
static int maxAreaOfIsland(vector< vector< int > > &grid)
static vector< int > findKDistantIndices(vector< int > &nums, int key, int k)
static int digArtifacts(int n, vector< vector< int > > &artifacts, vector< vector< int > > &dig)
static void calc_dist(int s, vector< pair< int, int > > *graph, vector< long long int > &dist)
static long long minimumWeight(int n, vector< vector< int > > &edges, int src1, int src2, int dest)
static bool validUtf8(vector< int > &data)
static vector< string > findRestaurant(vector< string > &list1, vector< string > &list2)
static int dfs(int current, int target, vector< int > nums)
AllOne()
Initializes the object of the data structure.
string getMaxKey()
Returns one of the keys with the maximal count.
string getMinKey()
Returns one of the keys with the minimum count.
map< int, unordered_set< string > > count_str
void dec(const string &key)
Decrements the count of the string key by 1. If the count of key is 0 after the decrement,...
unordered_map< string, int > str_count
void inc(const string &key)
Increments the count of the string key by 1. If key does not exist in the data structure,...
static string longestWord(vector< string > &words)
static string dfs(const string &str, TrieNode *node)
bool transfer(int account1, int account2, long long money)
Transfers money dollars from the account numbered account1 to the account numbered account2.
bool withdraw(int account, long long money)
Withdraw money dollars from the account numbered account.
bool deposit(int account, long long money)
Deposit money dollars into the account numbered account.
Bank(vector< long long > &balance)
Initializes the object with the 0-indexed integer array balance.
unordered_map< int, long long > accounts
static long long maximumSubsequenceCount(string text, string pattern)
static int minimumWhiteTiles(string floor, int numCarpets, int carpetLen)
static int countCollisions(const string &directions)
static vector< int > maximumBobPoints(int numArrows, vector< int > &aliceArrows)
static int networkBecomesIdle(vector< vector< int > > &edges, vector< int > &patience)
static bool findTarget(TreeNode *root, int k)
static vector< vector< int > > imageSmoother(vector< vector< int > > &img)
static int calPoints(vector< string > &ops)
static vector< long long > kthPalindrome(vector< int > &queries, int intLength)
static vector< int > missingRolls(vector< int > &rolls, int mean, int n)
static int maxConsecutiveAnswers(string answerKey, int k)
static vector< int > busiestServers(int k, vector< int > &arrival, vector< int > &load)
static vector< int > selfDividingNumbers(int left, int right)
static bool canReorderDoubled(vector< int > &arr)
static int strongPasswordChecker(const string &password)
static vector< vector< int > > findWinners(vector< vector< int > > &matches)
static int maximumCandies(vector< int > &candies, long long k)
Encrypter(vector< char > &keys, vector< string > &values, vector< string > &dictionary)
用 keys、values 和 dictionary 初始化 Encrypter 类。
int decrypt(const string &word2)
统计可以由 word2 解密得到且出现在 dictionary 中的字符串数目
string encrypt(const string &word1) const
按上述加密过程完成对 word1 的加密
NumArray(vector< int > &nums)
Initializes the object with the integer array nums.
void update(int index, int val)
Updates the value of nums[index] to be val.
int sumRange(int left, int right) const
Returns the sum of the elements of nums between indices left and right inclusive (i....
static vector< bool > friendRequests(int n, vector< vector< int > > &restrictions, vector< vector< int > > &requests)
static vector< int > findMinHeightTrees(int n, vector< vector< int > > &edges)
static int findLongestNode(int u, vector< int > &parent, vector< vector< int > > &adj)
static bool rotateString(string s, const string &goal)
Node(int _val, vector< Node * > _children)
static vector< vector< int > > levelOrder(Node *root)
static bool reachingPoints(int sx, int sy, int tx, int ty)
static int maximumProduct(vector< int > &nums, int k)
static long long maximumBeauty(vector< int > &flowers, long long newFlowers, int target, int full, int partial)
static vector< int > numberOfLines(vector< int > &widths, string s)
static bool checkInclusion(const string &s1, string s2)
int getRandom()
Returns a random element from the current set of elements (it's guaranteed that at least one element ...
bool insert(int val)
Inserts an item val into the set if not present.
RandomizedSet()
Initializes the RandomizedSet object.
bool remove(int val)
Removes an item val from the set if present.
static int projectionArea(vector< vector< int > > &grid)
int medium
The number of slots for medium parking space
ParkingSystem(int big, int medium, int small)
Initializes object of the ParkingSystem class.
int big
The number of slots for big parking space
bool addCar(int carType)
Checks whether there is a parking space of carType for the car that wants to get into the parking lot...
int small
The number of slots for small parking space
NumArray(vector< int > &nums)
Initializes the object with the integer array nums.
int sumRange(int left, int right) const
Returns the sum of the elements of nums between indices left and right inclusive (i....
static int rob(vector< int > &nums)
static int minimumTotal(vector< vector< int > > &triangle)
static TreeNode * lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
static void copy(TreeNode *tn, TreeNodeP *tnp, int low, int high, TreeNodeP **p, TreeNodeP **q)
vector< int > shuffle() const
Returns a random shuffling of the array.
Solution(vector< int > &nums)
Initializes the object with the integer array nums.
vector< int > reset()
Resets the array to its original configuration and returns it.
static vector< int > findAnagrams(string s, const string &p)
static int numSubarrayProductLessThanK(vector< int > &nums, int k)
static int minSubArrayLen(int target, vector< int > &nums)
static bool isSubtree(TreeNode *root, TreeNode *subRoot)
static bool equal(TreeNode *tn1, TreeNode *tn2)
static int shortestPathBinaryMatrix(vector< vector< int > > &grid)
static void solve(vector< vector< char > > &board)
static void dfs(vector< vector< char > > &board, int x, int y)
static int dfs(vector< vector< int > > &graph, vector< vector< int > > &ans, int cur)
static vector< vector< int > > allPathsSourceTarget(vector< vector< int > > &graph)
static vector< vector< int > > permuteUnique(vector< int > &nums)
static void dfs(set< vector< int > > &s, const vector< int > &current, vector< int > rest)
static vector< vector< int > > combinationSum(vector< int > &candidates, int target)
static vector< vector< int > > recurse(vector< int > &candidates, int target, int index)
static vector< vector< int > > combinationSum2(vector< int > &candidates, int target)
static vector< vector< int > > recurse(vector< int > &candidates, int target, int index)
static int rob(vector< int > &nums)
static bool canJump(vector< int > &nums)
static int jump(vector< int > &nums)
static int uniquePaths(int m, int n)
static int numberOfArithmeticSlices(vector< int > &nums)
static void search(const TrieNode *tn, const string &s, int i, vector< bool > &end)
static bool wordBreak(const string &s, vector< string > &wordDict)
static int longestCommonSubsequence(string text1, string text2)
static int minDistance(const string &word1, const string &word2)
static int minDistance(string word1, string word2)
static int coinChange(vector< int > &coins, int amount)
static int maxPoints(vector< vector< int > > &points)
static vector< vector< string > > groupAnagrams(vector< string > &strs)
static void qsort(vector< int > &nums, int l, int r)
static void sortColors(vector< int > &nums)
static vector< int > topKFrequent(vector< int > &nums, int k)
static int findKthLargest(vector< int > &nums, int k)
static vector< vector< int > > merge(vector< vector< int > > &intervals)
static bool searchMatrix(vector< vector< int > > &matrix, int target)
static bool search(const vector< vector< int > > &matrix, int target, int x_start, int x_end, int y_start, int y_end)
static TreeNode * deserialize(string data)
Decodes your encoded data to tree.
static string serialize(TreeNode *root)
Encodes a tree to a single string.
static int leastInterval(vector< char > &tasks, int n)
MyHashMap()
initializes the object with an empty map.
void put(int key, int value)
inserts a (key, value) pair into the HashMap. If the key already exists in the map,...
void remove(int key)
removes the key and its corresponding value if the map contains the mapping for the key.
array< list< pair< int, int > >, SZ > arr
static vector< vector< int > > generateMatrix(int n)
static int eraseOverlapIntervals(vector< vector< int > > &intervals)
static vector< int > productExceptSelf(vector< int > &nums)
static int subarraySum(vector< int > &nums, int k)
static vector< int > partitionLabels(string s)
static vector< string > findRepeatedDnaSequences(string s)
int get(int index) const
Get the value of the indexth node in the linked list. If the index is invalid, return -1.
void deleteAtIndex(int index)
Delete the indexth node in the linked list, if the index is valid.
void addAtHead(int val)
Add a node of value val before the first element of the linked list. After the insertion,...
void addAtTail(int val)
Append a node of value val as the last element of the linked list.
void addAtIndex(int index, int val)
Add a node of value val before the indexth node in the linked list. If index equals the length of the...
MyLinkedList()
Initializes the MyLinkedList object.
TreeNode * deleteNode(TreeNode *root, int key)
static unsigned missing(vector< int > &nums, int i)
static int missingElement(vector< int > &nums, int k)
static vector< int > findPeakGridLR(vector< vector< int > > &mat, int l, int r)
static int get(vector< vector< int > > &mat, int i, int j)
static vector< int > findPeakGrid(vector< vector< int > > &mat)
static int count(vector< int > &sweetness, int x)
static int maximizeSweetness(vector< int > &sweetness, int k)
static vector< int > shortestDistanceColor(vector< int > &colors, vector< vector< int > > &queries)
static vector< int > minAvailableDuration(vector< vector< int > > &slots1, vector< vector< int > > &slots2, int duration)
static pair< int, int > merge(const vector< int > &vec1, const vector< int > &vec2)
static int countInRange(vector< int > &nums, int l, int r)
static int findDuplicate(vector< int > &nums)
static int trap(vector< int > &height)
static vector< vector< int > > findRLEArray(vector< vector< int > > &encoded1, vector< vector< int > > &encoded2)
static int cntMinFlip(vector< int > &nums, int len)
static int longestOnes(vector< int > &nums, int k)
static vector< int > maxSlidingWindow(vector< int > &nums, int k)
static string minWindow(string s, const string &t)
static bool valid(unordered_map< char, int > &ums, const unordered_map< char, int > &umt)
static void wallsAndGates(vector< vector< int > > &rooms)
size_t operator()(const pair< int, int > &p) const
bool operator()(const pair< int, int > &p1, const pair< int, int > &p2) const
static vector< vector< int > > pacificAtlantic(vector< vector< int > > &heights)
static vector< int > getLonelyNodes(TreeNode *root)
unordered_set< Node * > children
static vector< int > killProcess(vector< int > &pid, vector< int > &ppid, int kill)
static vector< int > distanceK(TreeNode *root, TreeNode *target, int k)
static int openLock(vector< string > &deadends, const string &target)
static int makeConnected(int n, vector< vector< int > > &connections)
static void dfs(int &edge_cnt, int &node_cnt, unordered_set< int > &vis, int node, vector< unordered_set< int > > &g)
bool operator()(const pair< int, Node * > &p1, const pair< int, Node * > &p2) const
static void tarjan(int prev, int &step, vector< int > &dfn, int node, vector< unordered_set< int > > &g, vector< int > &low, vector< vector< int > > &ans)
static vector< vector< int > > criticalConnections(int n, vector< vector< int > > &connections)
static vector< vector< int > > getFactorsWithMin(int n, int minimum)
static vector< vector< int > > getFactors(int n)
static string decodeString(string s)
static bool valid(const vector< vector< bool > > &board, int n, int x, int y)
static vector< string > toStringVec(const vector< vector< bool > > &board)
static void dfs(const vector< vector< bool > > &board, int line, int n, vector< vector< string > > &ans)
static vector< vector< string > > solveNQueens(int n)
static bool valid(const vector< vector< char > > &board, int x, int y, char num)
static bool dfs(const vector< vector< char > > &board, vector< vector< char > > &ans)
static void solveSudoku(vector< vector< char > > &board)
static bool isMatch(const string &s, const string &p)
static bool dfs(const string &s, const string &p, int si, int pi)
static vector< int > diffWaysToCompute(const string &expression)
static vector< int > eval(const string &expr, int start, int end)
static vector< string > removeInvalidParentheses(const string &s)
static double findMedianSortedArrays(vector< int > &nums1, vector< int > &nums2)
static int get_m(const vector< int > &nums, int msum)
static int splitArray(vector< int > &nums, int m)
size_t operator()(const pair< TreeNode *, bool > &p) const
bool operator()(const pair< TreeNode *, bool > &p1, const pair< TreeNode *, bool > &p2) const
int dfs(bool steal, TreeNode *node)
unordered_map< pair< TreeNode *, bool >, int, myhash, myeq > um
static int maximalSquare(vector< vector< char > > &matrix)
static int maximalRectangle(vector< vector< char > > &matrix)
static bool PredictTheWinner(vector< int > &nums)
static vector< vector< string > > partition(const string &s)
static void dfs(const vector< string > &current, const string &s, vector< vector< string > > &ans, int start, int cursor)
static bool is_palindromic(const string &s, int start, int end)
static bool canPartition(vector< int > &nums)
static int mincostTickets(vector< int > &days, vector< int > &costs)
static int calculateMinimumHP(vector< vector< int > > &dungeon)
static bool canFinish(int numCourses, vector< vector< int > > &prerequisites)
static vector< int > findOrder(int numCourses, vector< vector< int > > &prerequisites)
int longestIncreasingPath(vector< vector< int > > &matrix)
static int minimumSemesters(int n, vector< vector< int > > &relations)
static string alienOrder(vector< string > &words)
static vector< int > singleNumber(vector< int > &nums)
static int shortestPathAllKeys(vector< string > &grid)
unordered_map< string, unordered_map< string, vector< int > > > um
unordered_map< int, pair< string, int > > records
void checkOut(int id, const string &stationName, int t)
通行卡 ID 等于 id 的乘客,在时间 t ,从 stationName 站离开
double getAverageTime(const string &startStation, const string &endStation)
平均时间会根据截至目前所有从 startStation 站 直接 到达 endStation 站的行程进行计算,也就是从 startStation 站进入并从 endStation 离开的行程 从 st...
void checkIn(int id, const string &stationName, int t)
通行卡 ID 等于 id 的乘客,在时间 t ,从 stationName 站进入 乘客一次只能从一个站进入
void put(int key, int value)
如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。
LRUCache(int capacity)
以 正整数 作为容量 capacity 初始化 LRU 缓存
int get(int key)
如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
unordered_map< int, int > um
TimeMap()=default
初始化数据结构对象
string get(const string &key, int timestamp)
返回先前调用 set(key, value, timestamp_prev) 所存储的值,其中 timestamp_prev <= timestamp 。
unordered_map< string, map< int, string, greater< int > > > um
void set(const string &key, string value, int timestamp)
存储键 key、值 value,以及给定的时间戳 timestamp。
void assign(unsigned l, unsigned r, type val=false)
bool check(unsigned l, unsigned r)
Node(unsigned l, unsigned r=0, type data=false)
bool operator<(const Node &rhs) const
RangeModule()=default
初始化数据结构的对象。
void removeRange(int left, int right)
停止跟踪 半开区间 [left, right) 中当前正在跟踪的每个实数。
void addRange(int left, int right)
添加 半开区间 [left, right),跟踪该区间中的每个实数。添加与当前跟踪的数字部分重叠的区间时,应当添加在区间 [left, right) 中尚未跟踪的任何数字到该区间中。
bool queryRange(int left, int right)
只有在当前正在跟踪区间 [left, right) 中的每一个实数时,才返回 true ,否则返回 false 。
int get(int key)
如果键 key 存在于缓存中,则获取键的值,否则返回 -1 。
unordered_map< int, int > um
map< int, list< int > > tnc
LFUCache(int capacity)
用数据结构的容量 capacity 初始化对象
unordered_map< int, int > cnt
void put(int key, int value)
如果键 key 已存在,则变更其值;如果键不存在,请插入键值对。当缓存达到其容量 capacity 时,则应该在插入新项之前,移除最不经常使用的项。在此问题中,当存在平局(即两个或更多个键具有相同使用频...
vector< unordered_map< int, int > > mem
int fourSumCount(vector< int > &nums1, vector< int > &nums2, vector< int > &nums3, vector< int > &nums4)
vector< unordered_map< int, int > > vec
static int maxSubArrayLen(vector< int > &nums, int k)
字典树节点