repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
ooooo-youwillsee/leetcode | lcof_068-2/cpp_068-2/Solution1.h | //
// Created by ooooo on 2020/4/26.
//
#ifndef CPP_068_2__SOLUTION1_H_
#define CPP_068_2__SOLUTION1_H_
#include "TreeNode.h"
#include <vector>
class Solution {
public:
bool dfs(TreeNode *node, TreeNode *p, vector<TreeNode *> &pNodes) {
if (!node) return false;
if (node->val == p->val || dfs(node->left, p, pNodes)
|| dfs(node->right, p, pNodes)) {
pNodes.push_back(node);
return true;
}
return false;
}
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
if (!root) return nullptr;
if (p == q) return p;
vector<TreeNode *> pNodes, qNodes;
dfs(root, p, pNodes);
dfs(root, q, qNodes);
for (int i = pNodes.size() - 1, j = qNodes.size() - 1; i >= 0 && j >= 0; --i, --j) {
if (pNodes[i] != qNodes[j]) return pNodes[i + 1];
}
return pNodes.size() < qNodes.size() ? pNodes[0] : qNodes[0];
}
};
#endif //CPP_068_2__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0052-N-Queens-II/cpp_0052/Solution1.h | <gh_stars>10-100
//
// Created by ooooo on 2019/12/7.
//
#ifndef CPP_0052_SOLUTION1_H
#define CPP_0052_SOLUTION1_H
class Solution {
private:
int total = 0;
int n;
void dfs(int row, int col, int pie, int na) {
if (row >= n) {
total += 1;
return;
}
int bits = ~(col | pie | na) & ((1 << n) - 1);
while (bits) {
int bit = bits & -bits;
dfs(row + 1, (col | bit), (pie | bit) << 1, (na | bit) >> 1);
bits = bits & (bits - 1);
}
}
public:
int totalNQueens(int n) {
total = 0;
this->n = n;
dfs(0, 0, 0, 0);
return total;
}
};
#endif //CPP_0052_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0054-Spiral Matrix/cpp_0054/Solution1.h | <reponame>ooooo-youwillsee/leetcode
/**
* @author ooooo
* @date 2020/10/5 17:16
*/
#ifndef CPP_0054__SOLUTION1_H_
#define CPP_0054__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
/*
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
*/
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>> &matrix) {
if (matrix.empty()) return {};
int m = matrix.size(), n = matrix[0].size();
vector<int> ans;
int size = m * n;
for (int c = 0; c < m / 2 + 1; c++) {
for (int i = 0 + c; i < n - 1 - c && size > 0; i++) {
ans.push_back(matrix[c][i]);
size--;
}
for (int i = 0 + c; i < m - 1 - c && size > 0; i++) {
ans.push_back(matrix[i][n - 1 - c]);
size--;
}
for (int i = 0 + c; i < n - 1 - c && size > 0; i++) {
ans.push_back(matrix[m - 1 - c][n - 1 - i]);
size--;
}
for (int i = 0 + c; i < m - 1 - c && size > 0; i++) {
ans.push_back(matrix[m - 1 - i][c]);
size--;
}
}
if (size) ans.push_back(matrix[m / 2][n / 2]);
return ans;
}
};
#endif //CPP_0054__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0086-Partition List/cpp_0086/ListNode.h | <gh_stars>10-100
/**
* @author ooooo
* @date 2021/1/4 16:15
*/
#ifndef CPP_0086__LISTNODE_H_
#define CPP_0086__LISTNODE_H_
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
#endif //CPP_0086__LISTNODE_H_
|
ooooo-youwillsee/leetcode | 0987-Vertical Order Traversal of a Binary Tree/cpp_0987/TreeNode.h | /**
* @author ooooo
* @date 2021/2/17 17:19
*/
#ifndef CPP_0987__TREENODE_H_
#define CPP_0987__TREENODE_H_
#include <vector>
#include <map>
#include <set>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
#endif //CPP_0987__TREENODE_H_
|
ooooo-youwillsee/leetcode | 1701-Average Waiting Time/cpp_1701/Solution1.h | /**
* @author ooooo
* @date 2021/1/24 18:08
*/
#ifndef CPP_1701__SOLUTION1_H_
#define CPP_1701__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
class Solution2 {
double averageWaitingTime(vector<vector<int>> &customers) {
long long total_wait = 0;
int n = customers.size();
long long last_finish = 0;
for (int i = 0; i < n; ++i) {
long long cur_time = 0;
if (customers[i][0] >= last_finish) {
cur_time = customers[i][0];
} else {
cur_time = last_finish;
}
total_wait += cur_time + customers[i][1] - customers[i][0];
last_finish = cur_time + customers[i][1];
}
return 1.0 * total_wait / n;
}
};
#endif //CPP_1701__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0303-Range-Sum-Query-Immutable/cpp_0303/Solution1.h | <filename>0303-Range-Sum-Query-Immutable/cpp_0303/Solution1.h
//
// Created by ooooo on 2020/1/29.
//
#ifndef CPP_0303__SOLUTION1_H_
#define CPP_0303__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class NumArray {
public:
int *sum;
NumArray(vector<int> &nums) {
sum = new int[nums.size() + 1];
sum[0] = 0;
for (int i = 0; i < nums.size(); ++i) {
sum[i + 1] = sum[i] + nums[i];
}
}
int sumRange(int i, int j) {
return sum[j + 1] - sum[i];
}
};
#endif //CPP_0303__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0140-Word Break II/cpp_0140/Solution1.h | /**
* @author ooooo
* @date 2020/11/1 10:24
*/
#ifndef CPP_0140__SOLUTION1_H_
#define CPP_0140__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
int min_len = INT_MAX, max_len = INT_MIN;
unordered_set<string> set;
vector<string> dfs(string &s, int i) {
vector<string> ans;
if (i >= s.size()) {
ans.push_back("");
return ans;
}
for (int j = min_len; j <= max_len; ++j) {
if (i + j > s.size()) continue;
string word = s.substr(i, j);
if (set.count(word)) {
vector<string> sentences = dfs(s, i + j);
for (auto sentence: sentences) {
ans.push_back(sentence == "" ? word + sentence : word + " " + sentence);
}
}
}
return ans;
}
bool exist(string s) {
vector<bool> dp(s.length() + 1, false);
// 0 表示空字符串
dp[0] = true;
for (int i = 1; i <= s.length(); ++i) {
for (int j = 0; j < i; ++j) {
if (dp[j] && set.count(s.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
vector<string> wordBreak(string s, vector<string> &wordDict) {
for (int i = 0; i < wordDict.size(); ++i) {
min_len = min(min_len, (int) wordDict[i].size());
max_len = max(max_len, (int) wordDict[i].size());
set.insert(wordDict[i]);
}
if (!exist(s)) return {};
return dfs(s, 0);
}
};
#endif //CPP_0140__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcof_018/cpp_018/Solution2.h | <reponame>ooooo-youwillsee/leetcode
//
// Created by ooooo on 2020/3/13.
//
#ifndef CPP_018__SOLUTION2_H_
#define CPP_018__SOLUTION2_H_
#include "ListNode.h"
/**
* 把后面的值逐一复制到 delNode 的 val
*/
class Solution {
public:
ListNode *deleteNode(ListNode *head, int val) {
ListNode *dummyHead = new ListNode(0), *prev = dummyHead;
dummyHead->next = head;
while (prev->next) {
if (prev->next->val == val) break;
prev = prev->next;
}
ListNode *cur = prev->next;
while (cur && cur->next) {
ListNode *next = cur->next;
cur->val = next->val;
cur = cur->next;
prev = prev->next;
}
prev->next = nullptr;
return dummyHead->next;
}
};
#endif //CPP_018__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0349-Intersection-of-Two-Arrays/cpp_0349/Solution1.h | <gh_stars>10-100
//
// Created by ooooo on 2019/12/29.
//
#ifndef CPP_0349_SOLUTION1_H
#define CPP_0349_SOLUTION1_H
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
vector<int> intersection(vector<int> &nums1, vector<int> &nums2) {
unordered_set<int> set(nums1.size());
for (const auto &num : nums1) {
set.insert(num);
}
vector<int> res;
for (const auto &num : nums2) {
if (set.find(num) != set.end()) {
set.erase(num);
res.push_back(num);
}
}
return res;
}
};
#endif //CPP_0349_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 1737-Change Minimum Characters to Satisfy One of Three Conditions/cpp_1737/Solution1.h | <reponame>ooooo-youwillsee/leetcode
/**
* @author ooooo
* @date 2021/2/28 13:13
*/
#ifndef CPP_1737__SOLUTION1_H_
#define CPP_1737__SOLUTION1_H_
#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <stack>
#include <vector>
#include <numeric>
using namespace std;
class Solution {
public:
int calc(vector<int> &count1, vector<int> &count2) {
int ans = INT_MAX;
int prevCount = 0;
for (int i = 25; i >= 1; --i) {
int count = count1[i] == 0 ? prevCount : count1[i] + prevCount;
prevCount = count;
for (int j = 0; j < i; ++j) {
count += count2[j];
}
ans = min(ans, count);
}
return ans;
}
int minCharacters(string a, string b) {
vector<int> count1(26), count2(26);
unordered_map<char, int> m;
int maxSameCount = 0;
for (int i = 0; i < a.size(); ++i) {
count1[a[i] - 'a']++;
m[a[i]]++;
maxSameCount = max(maxSameCount, m[a[i]]);
}
for (int i = 0; i < b.size(); ++i) {
count2[b[i] - 'a']++;
m[b[i]]++;
maxSameCount = max(maxSameCount, m[b[i]]);
}
int ans = a.size() + b.size();
ans = min(ans, calc(count1, count2));
ans = min(ans, calc(count2, count1));
ans = min(ans, (int) a.size() + (int) b.size() - maxSameCount);
return ans;
}
};
#endif //CPP_1737__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcof_004/cpp_004/Solution1.h | <reponame>ooooo-youwillsee/leetcode
//
// Created by ooooo on 2020/3/6.
//
#ifndef CPP_004__SOLUTION1_H_
#define CPP_004__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* O(m+n)
*/
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>> &matrix, int target) {
if (matrix.empty()) return false;
int m = matrix.size(), n = matrix[0].size();
int i = 0, j = n - 1;
while (i < m && j >= 0) {
int num = matrix[i][j];
if (target > num) {
i++;
} else if (target < num) {
j--;
} else {
return true;
}
}
return false;
}
};
#endif //CPP_004__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcof_048/cpp_048/Solution2.h | //
// Created by ooooo on 2020/4/5.
//
#ifndef CPP_048__SOLUTION2_H_
#define CPP_048__SOLUTION2_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* dp[i] = dp[i-1] + 1
*
* dp[i] 表示以第 i 个字符为尾的长度
*/
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.size(), ans = 0;
// map 中的 -1 表示没有出现过, >0 表示出现的索引位置
vector<int> dp(n + 1, 0), map(256, -1);
for (int i = 0; i < n; ++i) {
int preIndex = map[s[i]];
if (preIndex == -1) {
dp[i + 1] = dp[i] + 1;
} else {
int diff = i - preIndex;
if (diff <= dp[i]) {
dp[i + 1] = diff;
} else {
dp[i + 1] = dp[i] + 1;
}
}
map[s[i]] = i;
ans = max(ans, dp[i + 1]);
}
return ans;
}
};
#endif //CPP_048__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0211-Add-and-Search-Word-Data-structure-design/cpp_0211/Solution1.h | //
// Created by ooooo on 2020/2/7.
//
#ifndef CPP_0211__SOLUTION1_H_
#define CPP_0211__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class WordDictionary {
private:
struct Node {
bool isWord;
vector<Node *> next;
Node() : isWord(false), next(26, nullptr) {}
};
Node *root;
public:
/** Initialize your data structure here. */
WordDictionary() {
root = new Node();
}
/** Adds a word into the data structure. */
void addWord(string word) {
add(root, word, 0);
}
void add(Node *node, string word, int i) {
if (i == word.size()) {
node->isWord = true;
return;
}
char c = word[i];
if (node->next[c - 'a'] == nullptr) {
node->next[c - 'a'] = new Node();
}
add(node->next[c - 'a'], word, i + 1);
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool search(string word) {
return search(root, word, 0);
}
bool search(Node *node, string &word, int i) {
if (!node) return false;
if (i == word.size()) {
return node->isWord;
}
char c = word[i];
if (c == '.') {
for (auto &item: node->next) {
if (search(item, word, i + 1)) return true;
}
return false;
}
return search(node->next[c - 'a'], word, i + 1);
}
};
#endif //CPP_0211__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0279-Perfect-Squares/cpp_0279/Solution2.h | //
// Created by ooooo on 2020/2/23.
//
#ifndef CPP_0279__SOLUTION2_H_
#define CPP_0279__SOLUTION2_H_
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
/**
* dp[i] = min (dp[i-1] + dp[1]), ( dp[i-2] + dp[2] ) ,,, (dp[0] + dp[i])
* timeout
*/
class Solution {
public:
int numSquares(int n) {
vector<int> dp(n + 1, INT_MAX);
for (int i = int(sqrt(n)); i >= 1; --i) {
int index = i * i;
if (index == n) return 1;
dp[index] = 1;
}
for (int i = 1; i <= n; ++i) {
if (dp[i] == 1) continue;
for (int j = 1; j < i; ++j) {
dp[i] = min(dp[i - j] + dp[j], dp[i]);
}
}
return dp[n];
}
};
#endif //CPP_0279__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0045-Jump Game II/cpp_0045/Solution2.h | /**
* @author ooooo
* @date 2021/6/4 20:21
*/
#ifndef CPP_0045__SOLUTION2_H_
#define CPP_0045__SOLUTION2_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* 从0到n-1 循环获取,贪心
*/
class Solution {
public:
int jump(vector<int> &nums) {
int n = nums.size();
int last = n - 1;
int ans = 0;
while (last > 0) {
for (int i = 0; i < last; i++) {
if (nums[i] + i >= last) {
last = i;
ans++;
break;
}
}
}
return ans;
}
};
#endif //CPP_0045__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0377-Combination Sum IV/cpp_0377/Solution2.h | <filename>0377-Combination Sum IV/cpp_0377/Solution2.h
/**
* @author ooooo
* @date 2021/4/24 11:13
*/
#ifndef CPP_0377__SOLUTION2_H_
#define CPP_0377__SOLUTION2_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int combinationSum4(vector<int> &nums, int target) {
int n = nums.size();
vector<int> dp(target + 1);
dp[0] = 1;
for (int i = 1; i <= target; i++) {
for (int j = 0; j < n; j++) {
if (i >= nums[j] && dp[i] < INT_MAX - dp[i - nums[j]]) {
dp[i] += dp[i - nums[j]];
}
}
}
return dp[target];
}
};
#endif //CPP_0377__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0696-Count-Binary-Substrings/cpp_0696/Solution1.h | //
// Created by ooooo on 2020/1/30.
//
#ifndef CPP_0696__SOLUTION1_H_
#define CPP_0696__SOLUTION1_H_
#include <iostream>
using namespace std;
/**
* 暴力法
*/
class Solution {
public:
bool valid(string &s, int left, int right) {
char leftC = s[left++], rightC = s[right--];
if (leftC == rightC) return false;
while (left < right) {
if (s[left] != leftC || s[right] != rightC || s[left++] == s[right--]) return false;
}
return true;
}
int countBinarySubstrings(string s) {
int ans = 0;
for (int i = 2; i <= s.size(); i += 2) {
// 每一个j都扫描一遍
for (int j = 0; j <= s.size() - i; j++) {
if (valid(s, j, j + i - 1)) {
ans += 1;
}
}
}
return ans;
}
};
#endif //CPP_0696__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0135-Candy/cpp_0135/Solution2.h | /**
* @author ooooo
* @date 2020/12/24 17:12
*/
#ifndef CPP_0135__SOLUTION2_H_
#define CPP_0135__SOLUTION2_H_
#include <iostream>
#include <map>
#include <vector>
#include <numeric>
using namespace std;
class Solution {
public:
int candy(vector<int> &ratings) {
int n = ratings.size();
vector<int> candy(n, 1);
for (int i = 1; i < n; ++i) {
if (ratings[i] > ratings[i - 1]) {
candy[i] = max(candy[i], candy[i - 1] + 1);
}
}
for (int i = n - 2; i >= 0; --i) {
if (ratings[i] > ratings[i + 1]) {
candy[i] = max(candy[i], candy[i + 1] + 1);
}
}
return accumulate(candy.begin(), candy.end(), 0);
}
};
#endif //CPP_0135__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | lcof_068-2/cpp_068-2/Solution2.h | <filename>lcof_068-2/cpp_068-2/Solution2.h<gh_stars>10-100
//
// Created by ooooo on 2020/4/26.
//
#ifndef CPP_068_2__SOLUTION2_H_
#define CPP_068_2__SOLUTION2_H_
#include "TreeNode.h"
class Solution {
public:
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
if (!root) return nullptr;
if (root == q || root == p) return root;
auto left = lowestCommonAncestor(root->left, p, q);
auto right = lowestCommonAncestor(root->right, p, q);
if (left && right) return root;
if (left) return left;
if (right) return right;
return nullptr;
}
};
#endif //CPP_068_2__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0368-Largest Divisible Subset/cpp_0368/Solution1.h | <reponame>ooooo-youwillsee/leetcode
/**
* @author ooooo
* @date 2021/4/23 19:52
*/
#ifndef CPP_0368__SOLUTION1_H_
#define CPP_0368__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int> &nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
vector<int> dp(n, 1);
int max_cnt = 1;
int max_value = 0;
for (int i = 1; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
if (nums[i] % nums[j] == 0) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
if (dp[i] > max_cnt) {
max_cnt = dp[i];
max_value = nums[i];
}
}
vector<int> ans;
if (max_cnt == 1) {
return {nums[0]};
}
for (int i = n - 1; i >= 0; i--) {
if (dp[i] == max_cnt && max_value % nums[i] == 0) {
ans.push_back(nums[i]);
max_cnt--;
max_value = nums[i];
}
}
return ans;
}
};
#endif //CPP_0368__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0325-Maximum Size Subarray Sum Equals k/cpp_0325/Solution1.h | /**
* @author ooooo
* @date 2021/6/4 20:52
*/
#ifndef CPP_0325__SOLUTION1_H_
#define CPP_0325__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_map>
class Solution {
public:
int maxSubArrayLen(vector<int> &nums, int k) {
int n = nums.size();
unordered_map<int, int> m;
m[0] = -1;
int ans = 0;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += nums[i];
if (m.find(sum - k) != m.end()) {
ans = max(ans, i - m[sum - k]);
}
if (m.find(sum) == m.end()) {
m[sum] = i;
}
}
return ans;
}
};
#endif //CPP_0325__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0299-Bulls-and-Cows/cpp_0299/Solution1.h | <filename>0299-Bulls-and-Cows/cpp_0299/Solution1.h
//
// Created by ooooo on 2020/1/10.
//
#ifndef CPP_0299__SOLUTION1_H_
#define CPP_0299__SOLUTION1_H_
#include <iostream>
#include <unordered_set>
#include <unordered_map>
using namespace std;
class Solution {
public:
string getHint(string secret, string guess) {
unordered_map<char, int> secretMap, guessMap;
int A = 0, B = 0;
for (int i = 0; i < guess.size(); ++i) {
if (guess[i] == secret[i]) {
A++;
} else {
secretMap[secret[i]]++;
guessMap[guess[i]]++;
}
}
for (auto &entry: guessMap) {
char key = entry.first;
if (secretMap.count(key)) {
if (secretMap[key] < guessMap[key]) {
B += secretMap[key];
} else {
B += guessMap[key];
}
}
}
return to_string(A) + "A" + to_string(B) + "B";
}
};
#endif //CPP_0299__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0987-Vertical Order Traversal of a Binary Tree/cpp_0987/Solution1.h | <reponame>ooooo-youwillsee/leetcode
/**
* @author ooooo
* @date 2021/2/17 17:19
*/
#ifndef CPP_0987__SOLUTION1_H_
#define CPP_0987__SOLUTION1_H_
#include "TreeNode.h"
class Solution {
public:
void dfs(TreeNode *root, vector<vector<vector<int>>> &ans, int col, int row) {
if (!root) {
return;
}
ans[col][row].push_back(root->val);
dfs(root->left, ans, col - 1, row + 1);
dfs(root->right, ans, col + 1, row + 1);
}
int leftWidth(TreeNode *root) {
if (!root) {
return 0;
}
return max(1 + leftWidth(root->left), leftWidth(root->right) - 1);
}
int rightWidth(TreeNode *root) {
if (!root) {
return 0;
}
return max(1 + rightWidth(root->right), rightWidth(root->left) - 1);
}
int getDepth(TreeNode *root) {
if (!root) {
return 0;
}
return max(getDepth(root->left), getDepth(root->right)) + 1;
}
vector<vector<int>> verticalTraversal(TreeNode *root) {
if (!root) return {};
int leftW = leftWidth(root), rightW = rightWidth(root), h = getDepth(root);
vector<vector<vector<int>>> ans(leftW + rightW - 1, vector<vector<int>>(h, vector<int>()));
dfs(root, ans, leftW - 1, 0);
vector<vector<int>> res(leftW + rightW - 1);
for (int i = 0; i < ans.size(); ++i) {
auto &cols = ans[i];
for (auto &row: cols) {
sort(row.begin(), row.end());
for (auto num: row) {
res[i].push_back(num);
}
}
}
return res;
}
};
#endif //CPP_0987__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0861-Score After Flipping Matrix/cpp_0861/Solution1.h | /**
* @author ooooo
* @date 2020/12/7 15:01
*/
#ifndef CPP_0861__SOLUTION1_H_
#define CPP_0861__SOLUTION1_H_
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
/**
* 判断左上角是否为1, 如果为0,可以flipX或者flipY, 后面的行只能flipX
*/
class Solution {
public:
vector<vector<int>> A;
int m, n;
int calcMax(vector<int> &first_cols, vector<int> &rows, vector<int> &cols) {
int ans = 0;
for (int i = 1; i < m; ++i) {
if (first_cols[i] == 0) {
flipX(i, 0, rows, cols);
}
}
ans += m * (int) pow(2, n - 1);
for (int j = 1; j < n; ++j) {
int k = max(cols[j], m - cols[j]);
ans += k * (int) pow(2, n -j - 1);
}
return ans;
}
void flipX(int i, int j, vector<int> &rows, vector<int> &cols) {
rows[i] = n - rows[i];
for (int k = 0; k < n; ++k) {
cols[k] = A[i][k] == 1 ? cols[k] - 1 : cols[k] + 1;
}
}
void flipY(int i, int j, vector<int> &rows, vector<int> &cols) {
cols[j] = m - cols[j];
for (int k = 0; k < m; ++k) {
rows[k] = A[k][j] == 1 ? rows[k] - 1 : rows[k] + 1;
}
}
int matrixScore(vector<vector<int>> &A) {
this->m = A.size();
this->n = A[0].size();
this->A = A;
vector<int> rows, cols;
rows.assign(m, 0);
cols.assign(n, 0);
vector<int> first_cols(m, 0);
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (A[i][j] == 1) {
rows[i]++;
cols[j]++;
}
if (j == 0) {
first_cols[i] = A[i][j];
}
}
}
int ans = 0;
if (A[0][0] == 0) {
// flipX
vector<int> new_rows1 = rows, new_cols1 = cols;
first_cols[0] = !first_cols[0];
flipX(0, 0, new_rows1, new_cols1);
ans = max(ans, calcMax(first_cols, new_rows1, new_cols1));
first_cols[0] = !first_cols[0];
// flipY
for (int i = 0; i < m; ++i) {
first_cols[i] = !first_cols[i];
}
vector<int> new_rows2 = rows, new_cols2 = cols;
flipY(0, 0, new_rows2, new_cols2);
ans = max(ans, calcMax(first_cols, new_rows2, new_cols2));
} else {
ans = max(ans, calcMax(first_cols, rows, cols));
}
return ans;
}
};
#endif //CPP_0861__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcof_036/cpp_036/Solution1.h | <reponame>ooooo-youwillsee/leetcode<gh_stars>10-100
//
// Created by ooooo on 2020/3/23.
//
#ifndef CPP_036__SOLUTION1_H_
#define CPP_036__SOLUTION1_H_
#include "Node.h"
class Solution {
public:
void dfs(Node *node) {
if (!node) return;
dfs(node->left);
if (!head) {
head = node;
prev = node;
} else {
prev->right = node;
node->left = prev;
prev = node;
}
dfs(node->right);
}
Node *head, *prev;
Node *treeToDoublyList(Node *root) {
if (!root) return nullptr;
dfs(root);
head->left = prev;
prev->right = head;
return head;
}
};
#endif //CPP_036__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0100-Same-Tree/cpp_0100/Solution1.h | //
// Created by ooooo on 2019/12/6.
//
#ifndef CPP_0100_SOLUTION1_H
#define CPP_0100_SOLUTION1_H
#include "TreeNode.h"
class Solution {
private:
bool dfs(TreeNode *p, TreeNode *q) {
if (!p && !q) {
return true;
} else if (!p || !q) {
return false;
}
return p->val == q->val && dfs(p->left, q->left) && dfs(p->right, q->right);
}
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
return dfs(p, q);
}
};
#endif //CPP_0100_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0155-Min-Stack/cpp_0155/Solution1.h | //
// Created by ooooo on 2019/12/30.
//
#ifndef CPP_0155_SOLUTION1_H
#define CPP_0155_SOLUTION1_H
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
class MinStack {
private:
vector<int> data;
int min = INT_MAX;
public:
/** initialize your data structure here. */
MinStack() {
min = INT_MAX;
data.clear();
}
void push(int x) {
min = x < min ? x : min;
data.push_back(x);
}
void pop() {
int v = top();
data.erase(end(data) - 1);
if (v == min) {
min = INT_MAX;
for (auto num : data) {
min = min < num ? min : num;
}
}
}
int top() {
return data[data.size() - 1];
}
int getMin() {
return min;
}
};
#endif //CPP_0155_SOLUTION1_H
|
ooooo-youwillsee/leetcode | lcof_017/cpp_017/Solution1.h | //
// Created by ooooo on 2020/3/13.
//
#ifndef CPP_017__SOLUTION1_H_
#define CPP_017__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
class Solution {
public:
vector<int> printNumbers(int n) {
int num = 1;
while (n--) num *= 10;
vector<int> ans(num - 1);
for (int i = 1; i < num; ++i) {
ans[i-1] = i;
}
return ans;
}
};
#endif //CPP_017__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 1780-Check if Number is a Sum of Powers of Three/cpp_1780/Solution1.h | <filename>1780-Check if Number is a Sum of Powers of Three/cpp_1780/Solution1.h<gh_stars>10-100
/**
* @author ooooo
* @date 2021/3/14 14:56
*/
#ifndef CPP_1780__SOLUTION1_H_
#define CPP_1780__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <stack>
#include <numeric>
#include <queue>
using namespace std;
class Solution {
public:
bool checkPowersOfThree(int n) {
int num = n;
while (num) {
if (num % 3 != 0) {
num--;
}
if (num % 3 != 0) return false;
num = num / 3;
}
return true;
}
};
#endif //CPP_1780__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0461-Hamming-Distance/cpp_0461/Solution1.h | <reponame>ooooo-youwillsee/leetcode<filename>0461-Hamming-Distance/cpp_0461/Solution1.h
//
// Created by ooooo on 2020/2/6.
//
#ifndef CPP_0461__SOLUTION1_H_
#define CPP_0461__SOLUTION1_H_
#include <iostream>
#include <sstream>
using namespace std;
/**
* 将数字转化为字符串,然后^操作
*/
class Solution {
public:
string help(int n) {
stringstream ss;
int i = 0;
while (n) {
ss << n % 2;
i += 1;
n /= 2;
}
ss << string(32 - i, '0');
return ss.str();
}
int hammingDistance(int x, int y) {
string x_str = help(x);
string y_str = help(y);
int ans = 0;
for (int i = 0; i < 32; ++i) {
if ((x_str[i] ^ y_str[i]) == 1) {
ans += 1;
}
}
return ans;
}
};
#endif //CPP_0461__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0690-Employee-Importance/cpp_0690/Employee.h | <gh_stars>10-100
//
// Created by ooooo on 2020/1/13.
//
#ifndef CPP_0690__EMPLOYEE_H_
#define CPP_0690__EMPLOYEE_H_
#include <iostream>
#include <vector>
using namespace std;
class Employee {
public:
// It's the unique ID of each node.
// unique id of this employee
int id;
// the importance value of this employee
int importance;
// the id of direct subordinates
vector<int> subordinates;
Employee(int id, int importance, const vector<int> &subordinates)
: id(id), importance(importance), subordinates(subordinates) {}
Employee() {}
};
#endif //CPP_0690__EMPLOYEE_H_
|
ooooo-youwillsee/leetcode | 0557-Reverse-Words-in-a-String-III/cpp_0557/Solution1.h | //
// Created by ooooo on 2020/1/28.
//
#ifndef CPP_0557__SOLUTION1_H_
#define CPP_0557__SOLUTION1_H_
#include <iostream>
using namespace std;
class Solution {
public:
string reverseWords(string s) {
s += " ";
int i = 0, j = s.find(" ", i);
while (j != -1) {
reverse(s.begin() + i, s.begin() + j);
i = j + 1;
j = s.find(" ", i);
}
return s.substr(0, s.size() - 1);
}
};
#endif //CPP_0557__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0188-Best Time to Buy and Sell Stock IV/cpp_0188/Solution1.h | /**
* @author ooooo
* @date 2020/12/28 16:31
*/
#ifndef CPP_0188__SOLUTION1_H_
#define CPP_0188__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* dp[i][j][n] 表示第i天进行第j次交易,持有n股
*/
class Solution {
public:
int maxProfit(int k, vector<int> &prices) {
int n = prices.size();
int ans = 0;
vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>(k + 1, vector<int>(2, 0)));
for (int i = 1; i <= k; ++i) {
dp[0][i][0] = -10000;
dp[0][i][1] = -10000;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < k; ++j) {
int p = prices[i];
dp[i + 1][j + 1][0] = max(dp[i][j + 1][0], dp[i][j + 1][1] + p);
dp[i + 1][j + 1][1] = max(dp[i][j + 1][1], dp[i][j][0] - p);
ans = max(ans, dp[i + 1][j + 1][0]);
}
}
return ans;
}
};
#endif //CPP_0188__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 1685-Sum of Absolute Differences in a Sorted Array/cpp_1685/Solution1.h | <filename>1685-Sum of Absolute Differences in a Sorted Array/cpp_1685/Solution1.h
/**
* @author ooooo
* @date 2020/12/20 13:07
*/
#ifndef CPP_1685__SOLUTION1_H_
#define CPP_1685__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <numeric>
#include <math.h>
using namespace std;
class Solution {
public:
vector<int> getSumAbsoluteDifferences(vector<int> &nums) {
int n = nums.size();
vector<int> sum(n);
sum[0] = nums[0];
for (int i = 1; i < n; ++i) {
sum[i] = sum[i - 1] + nums[i];
}
vector<int> ans(n, 0);
for (int i = 0; i < n; ++i) {
if (i > 0) {
ans[i] += (i * nums[i] - sum[i - 1]);
}
if (i < n) {
ans[i] += (sum[n - 1] - sum[i] - (n - 1 - i) * nums[i]);
}
}
return ans;
}
};
#endif //CPP_1685__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0748-Shortest-Completing-Word/cpp_0748/Solution1.h | <gh_stars>10-100
//
// Created by ooooo on 2020/1/14.
//
#ifndef CPP_0748__SOLUTION1_H_
#define CPP_0748__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool check(string word, unordered_map<char, int> &m) {
unordered_map<char, int> wordMap;
for (const auto &c: word) wordMap[c]++;
for (const auto &entry :m) {
if (entry.second > wordMap[entry.first]) return false;
}
return true;
}
string shortestCompletingWord(string licensePlate, vector<string> &words) {
unordered_map<char, int> m;
for (const auto &item: licensePlate) {
char c = tolower(item);
if (c >= 'a' && c <= 'z') m[c]++;
}
int index = INT_MAX;
string ans = "";
for (int i = 0; i < words.size(); ++i) {
if (check(words[i], m)) {
if (ans.empty() || words[i].size() < ans.size()
|| (words[i].size() == ans.size() && i < index)) {
ans = words[i];
index = i;
}
}
}
return ans;
}
};
#endif //CPP_0748__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcp-033/cpp_033/Solution1.h | <filename>lcp-033/cpp_033/Solution1.h
/**
* @author ooooo
* @date 2021/4/10 21:05
*/
#ifndef CPP_033__SOLUTION1_H_
#define CPP_033__SOLUTION1_H_
class Solution {
public:
int storeWater(vector<int> &bucket, vector<int> &vat) {
int n = bucket.size();
int a = 1;
int b = 0;
for (int i = 0; i < n; i++) {
if (bucket[i] == 0) {
b = max(b, vat[i]);
} else {
b = max(b, (int) ceil(1.0 * vat[i] / bucket[i]));
}
}
int ans = INT_MAX;
// 遍历倾倒次数
while (a <= b) {
int cur = a;
for (int i = 0; i < n; i++) {
if (vat[i] == 0) continue;
cur += max(0, (int) ceil(1.0 * vat[i] / a) - bucket[i]);
}
ans = min(ans, cur);
a++;
}
return ans == INT_MAX ? 0 : ans;
}
};
#endif //CPP_033__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0354-Russian Doll Envelopes/cpp_0354/Solution1.h | <gh_stars>10-100
/**
* @author ooooo
* @date 2021/3/4 12:09
*/
#ifndef CPP_0354__SOLUTION1_H_
#define CPP_0354__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxEnvelopes(vector<vector<int>> &envelopes) {
sort(envelopes.begin(), envelopes.end(), [](const auto &x, const auto &y) {
return x[0] == y[0] ? x[1] < y[1] : x[0] < y[0];
});
int n = envelopes.size();
vector<int> dp(n);
int ans = 0;
for (int i = 0; i < n; ++i) {
dp[i] = 1;
for (int j = i - 1; j >= 0; --j) {
if (envelopes[j][0] < envelopes[i][0] && envelopes[j][1] < envelopes[i][1]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
ans = max(ans, dp[i]);
}
return ans;
}
};
#endif //CPP_0354__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0304-Range Sum Query 2D - Immutable/cpp_0304/Solution1.h | <filename>0304-Range Sum Query 2D - Immutable/cpp_0304/Solution1.h
/**
* @author ooooo
* @date 2021/3/2 09:03
*/
#ifndef CPP_0304__SOLUTION1_H_
#define CPP_0304__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class NumMatrix {
public:
vector<vector<int>> preSum;
NumMatrix(vector<vector<int>> &matrix) {
if (matrix.empty()) {
return;
}
int m = matrix.size(), n = matrix[0].size();
preSum.assign(m, vector<int>(n + 1, 0));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
preSum[i][j + 1] = preSum[i][j] + matrix[i][j];
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
if (preSum.empty()) {
return 0;
}
int sum = 0;
for (int i = row1; i <= row2; ++i) {
sum += preSum[i][col2 + 1] - preSum[i][col1];
}
return sum;
}
};
#endif //CPP_0304__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0331-Verify Preorder Serialization of a Binary Tree/cpp_0331/Solution2.h | <gh_stars>10-100
/**
* @author ooooo
* @date 2021/3/12 20:00
*/
#ifndef CPP_0331__SOLUTION2_H_
#define CPP_0331__SOLUTION2_H_
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
// 插槽栈
class Solution {
public:
bool isValidSerialization(string preorder) {
stack<int> s;
s.push(1);
int i = 0, n = preorder.size();
while (i < n) {
if (preorder[i] == ',') {
i++;
} else if (preorder[i] == '#') {
if (s.empty()) {
return false;
}
s.top() -= 1;
if (s.top() == 0) {
s.pop();
}
i++;
} else {
while (i < n && preorder[i] != ',') {
i++;
}
i++;
if (s.empty()) {
return false;
}
s.top() -= 1;
if (s.top() == 0) {
s.pop();
}
s.push(2);
}
}
return s.empty();
}
};
#endif //CPP_0331__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0045-Jump Game II/cpp_0045/Solution3.h | /**
* @author ooooo
* @date 2021/6/4 20:38
*/
#ifndef CPP_0045__SOLUTION3_H_
#define CPP_0045__SOLUTION3_H_
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int jump(vector<int> &nums) {
int n = nums.size();
int ans = 0, end = 0, pos = 0;
for (int i = 0; i < n - 1; i++) {
pos = max(pos, i + nums[i]);
if (i == end) {
ans++;
end = pos;
}
}
return ans;
}
};
#endif //CPP_0045__SOLUTION3_H_
|
ooooo-youwillsee/leetcode | 0129-Sum Root to Leaf Numbers/cpp_0129/Solution1.h | <reponame>ooooo-youwillsee/leetcode
/**
* @author ooooo
* @date 2020/10/29 09:31
*/
#ifndef CPP_0129__SOLUTION1_H_
#define CPP_0129__SOLUTION1_H_
#include "TreeNode.h"
class Solution {
public:
int ans = 0;
void dfs(TreeNode *node, int cur) {
if (!node) return;
cur = cur * 10 + node->val;
if (!node->left && !node->right) {
ans += cur;
return;
}
dfs(node->left, cur);
dfs(node->right, cur);
}
int sumNumbers(TreeNode *root) {
dfs(root, 0);
return ans;
}
};
#endif //CPP_0129__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0456-132 Pattern/cpp_0456/Solution2.h | /**
* @author ooooo
* @date 2021/3/24 16:38
*/
#ifndef CPP_0456__SOLUTION2_H_
#define CPP_0456__SOLUTION2_H_
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
// o(n)
class Solution {
public:
bool find132pattern(vector<int> &nums) {
int n = nums.size();
if (n < 3) {
return false;
}
stack<int> maxStack;
int last = INT_MIN;
for (int i = n - 1; i >= 0; --i) {
if (nums[i] < last) {
return true;
}
while (!maxStack.empty() && maxStack.top() < nums[i]) {
last = maxStack.top();
maxStack.pop();
}
maxStack.push(nums[i]);
}
return false;
}
};
#endif //CPP_0456__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 1178-Number of Valid Words for Each Puzzle/cpp_1178/Solution1.h | /**
* @author ooooo
* @date 2021/2/26 13:28
*/
#ifndef CPP_1178__SOLUTION1_H_
#define CPP_1178__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> findNumOfValidWords(vector<string> &words, vector<string> &puzzles) {
// 对words去重, 其中int为每个word单词表示,重复的单词数加1
unordered_map<int, int> wordMap;
for (int i = 0; i < words.size(); ++i) {
int bit = 0;
for (int j = 0; j < words[i].size(); ++j) {
int c = words[i][j] - 'a';
bit |= (1 << c);
}
wordMap[bit]++;
}
vector<int> ans(puzzles.size(), 0);
for (int i = 0; i < puzzles.size(); ++i) {
int cnt = 0;
// 每个字符串逐一匹配 (低效操作)
/*for (auto[word, count]: wordMap) {
// word 没有第一个字符
if (((1 << (puzzles[i][0] - 'a')) & word) == 0) {
continue;
}
if (bitset<26>(word & mask).count() == bitset<26>(word).count()) {
cnt += count;
}
}*/
int mask = 0;
for (int j = 1; j < 7; ++j) {
mask |= (1 << (puzzles[i][j] - 'a'));
}
int subset = mask;
do {
int s = subset | (1 << (puzzles[i][0] - 'a'));
if (wordMap.count(s)) {
cnt += wordMap[s];
}
// 就取mask为1的位置
subset = (subset - 1) & mask;
} while (subset != mask);
ans[i] = cnt;
}
return ans;
}
};
#endif //CPP_1178__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 1489-Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/cpp_1489/Solution1.h | <filename>1489-Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/cpp_1489/Solution1.h
/**
* @author ooooo
* @date 2021/1/21 20:36
*/
#ifndef CPP_1489__SOLUTION1_H_
#define CPP_1489__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
class Solution {
public:
struct UF {
int n;
vector<int> p;
UF(int n) : n(n), p(n) {
for (int i = 0; i < p.size(); ++i) {
p[i] = i;
}
}
int find(int i) {
if (p[i] == i) return i;
return p[i] = find(p[i]);
}
bool connected(int i, int j) {
int pi = find(i), pj = find(j);
if (pi == pj) return true;
p[pi] = pj;
n--;
return false;
}
int size() {
return n;
}
};
vector<vector<int>> findCriticalAndPseudoCriticalEdges(int n, vector<vector<int>> &edges) {
vector<pair<int, vector<int>>> g;
for (int i = 0; i < edges.size(); ++i) {
g.emplace_back(i, edges[i]);
}
auto comp = [](auto &x, auto &y) {
return x.second[2] < y.second[2];
};
sort(g.begin(), g.end(), comp);
UF uf(n);
// 计算最小生成树
int minTotalWeight = 0;
int count = 1;
for (auto &[i, edge]: g) {
int x = edge[0], y = edge[1], w = edge[2];
if (!uf.connected(x, y)) {
minTotalWeight += w;
count++;
if (count == n) {
break;
}
}
}
vector<vector<int>> ans(2, vector<int>());
for (int i = 0; i < edges.size(); ++i) {
// 计算关键边
int totalWeight = 0;
count = 1;
uf = UF(n);
for (auto &[j, edge]: g) {
// 不要i下标
if (j == i) continue;
int x = edge[0], y = edge[1], w = edge[2];
if (!uf.connected(x, y)) {
totalWeight += w;
count++;
if (count == n) break;
}
}
if (uf.size() != 1 || totalWeight > minTotalWeight) {
ans[0].push_back(i);
continue;
}
// 计算伪关键边, 主要是看能不能组成最小生成树
uf = UF(n);
totalWeight = edges[i][2];
uf.connected(edges[i][0], edges[i][1]);
count = 1;
for (auto &[j, edge]: g) {
int x = edge[0], y = edge[1], w = edge[2];
if (!uf.connected(x, y)) {
totalWeight += w;
count++;
if (count == n) break;
}
}
if (totalWeight == minTotalWeight) {
ans[1].push_back(i);
}
}
return ans;
}
};
#endif //CPP_1489__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 1702-Maximum Binary String After Change/cpp_1702/Solution1.h | <filename>1702-Maximum Binary String After Change/cpp_1702/Solution1.h
/**
* @author ooooo
* @date 2021/1/24 18:09
*/
#ifndef CPP_1702__SOLUTION1_H_
#define CPP_1702__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
class Solution2 {
string maximumBinaryString(string b) {
int n = b.size();
int cnt_0 = 0;
for (auto c: b) {
if (c == '0') cnt_0++;
}
int prev_is_1 = 0;
for (auto c: b) {
if (c == '0') {
break;
}
prev_is_1++;
}
int last_is_1 = n - cnt_0 - prev_is_1;
string ans(prev_is_1, '1');
if (cnt_0 > 0) {
ans += string(cnt_0 - 1, '1') + '0';
}
ans += string(last_is_1, '1');
return ans;
}
};
#endif //CPP_1702__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0718-Maximum-Length-of-Repeated-Subarray/cpp_0718/Solution2.h | <filename>0718-Maximum-Length-of-Repeated-Subarray/cpp_0718/Solution2.h
/**
* @author ooooo
* @date 2020/10/5 13:15
*/
#ifndef CPP_0718__SOLUTION2_H_
#define CPP_0718__SOLUTION2_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int findLength(vector<int> &A, vector<int> &B) {
int m = A.size(), n = B.size();
int ans = 0;
vector<int> dp(n + 1, 0);
// cout<<endl;
int prev = 0, help = 0;
for (int i = 0; i < m; i++) {
help = 0;
for (int j = 0; j < n; j++) {
prev = help;
help = dp[j + 1]; // 保留上个状态,避免被覆盖
if (A[i] == B[j]) {
dp[j + 1] = prev + 1;
ans = max(ans, dp[j + 1]);
} else {
dp[j + 1] = 0;
}
// cout << " i: "<< i <<" j: " << j << " : " << dp[j+1] << "\t ";
}
// cout<< endl;
}
return ans;
}
};
#endif //CPP_0718__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0399-Evaluate Division/cpp_0399/Solutoin1.h | <filename>0399-Evaluate Division/cpp_0399/Solutoin1.h
/**
* @author ooooo
* @date 2021/1/6 09:33
*/
#ifndef CPP_0399__SOLUTOIN1_H_
#define CPP_0399__SOLUTOIN1_H_
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <queue>
using namespace std;
class Solution {
public:
// 图
unordered_map<string, vector<string>> g;
// 对应的权值
unordered_map<string, vector<double>> vs;
unordered_set<string> visited;
double dfs(string u, string v, double y) {
visited.insert(u);
for (int j = 0; j < g[u].size(); ++j) {
auto x = g[u][j];
if (visited.count(x)) continue;
if (x == v) {
return y * vs[u][j];
}
double res = dfs(x, v, y * vs[u][j]);
if (res != -1) {
return res;
}
}
return -1.0;
}
vector<double> calcEquation(vector<vector<string>> &equations,
vector<double> &values,
vector<vector<string>> &queries) {
unordered_set<string> all;
for (int i = 0; i < equations.size(); ++i) {
string u = equations[i][0], v = equations[i][1];
double uv = values[i], vv = 1 / values[i];
g[u].push_back(v);
g[v].push_back(u);
vs[u].push_back(uv);
vs[v].push_back(vv);
all.insert(u);
all.insert(v);
}
vector<double> ans(queries.size());
for (int i = 0; i < queries.size(); ++i) {
string u = queries[i][0], v = queries[i][1];
// 不存在为-1
if (!all.count(u) || !all.count(v)) {
ans[i] = -1;
continue;
}
// 相等为1
if (u == v) {
ans[i] = 1;
continue;
}
visited.clear();
ans[i] = dfs(u, v, 1.0);
}
return ans;
}
};
#endif //CPP_0399__SOLUTOIN1_H_
|
ooooo-youwillsee/leetcode | 0720-Longest-Word-in-Dictionary/cpp_0720/Solution2.h | //
// Created by ooooo on 2020/1/14.
//
#ifndef CPP_0720__SOLUTION2_H_
#define CPP_0720__SOLUTION2_H_
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/**
* 哈希表
*/
class Solution {
public:
bool check(string word, unordered_set<string> &s) {
for (int i = word.size(); i >= 1; --i) {
if (!s.count(word.substr(0, i))) return false;
}
return true;
}
string longestWord(vector<string> &words) {
unordered_map<int, vector<string>> m;
unordered_set<string> s;
int maxLen = INT_MIN;
for (const auto &word: words) {
s.insert(word);
int len = word.size();
maxLen = max(maxLen, len);
if (m.count(len)) {
m[len].push_back(word);
} else {
m[len] = {word};
}
}
for (int i = maxLen; i > 0; --i) {
string ans = "";
for (auto &word: m[i]) {
if (check(word, s) && (ans.size() < word.size() || (ans.size() == word.size() && ans > word))) {
ans = word;
}
}
if (!ans.empty()) return ans;
}
return "";
}
};
#endif //CPP_0720__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0139-Word-Break/cpp_0139/Solution2.h | <filename>0139-Word-Break/cpp_0139/Solution2.h
//
// Created by ooooo on 2020/2/17.
//
#ifndef CPP_0139__SOLUTION2_H_
#define CPP_0139__SOLUTION2_H_
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
/**
* 记忆化 记录索引 i 的位置
*/
class Solution {
public:
unordered_set<string> word_set;
vector<int> memo;
bool help(string s, int i) {
if (i == s.length()) return true;
if (memo[i] != 0) return memo[i] == 1;
for (int j = i + 1; j <= s.length(); j++) {
if (word_set.count(s.substr(i, j - i)) && help(s, j)) {
memo[i] = 1;
return true;
}
}
memo[i] = 2;
return false;
}
bool wordBreak(string s, vector<string> &wordDict) {
word_set.insert(wordDict.begin(), wordDict.end());
// 0 表示没有访问过, 1 表示 true, 2 表示 false
memo.assign(s.length(), 0);
return help(s, 0);
}
};
#endif //CPP_0139__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0090-Subsets II/cpp_0090/Solution1.h | <filename>0090-Subsets II/cpp_0090/Solution1.h<gh_stars>10-100
/**
* @author ooooo
* @date 2021/3/31 09:58
*/
#ifndef CPP_0090__SOLUTION1_H_
#define CPP_0090__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> ans;
void dfs(vector<int> &nums, int i, vector<int> &tmp) {
ans.push_back(tmp);
for (int j = i; j < nums.size(); j++) {
if (j > i && nums[j] == nums[j - 1]) continue;
tmp.push_back(nums[j]);
dfs(nums, j + 1, tmp);
tmp.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int> &nums) {
sort(nums.begin(), nums.end());
vector<int> tmp = {};
dfs(nums, 0, tmp);
return ans;
}
};
#endif //CPP_0090__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0136-Single-Number/cpp_0136/Solution2.h | //
// Created by ooooo on 2019/12/30.
//
#ifndef CPP_0136_SOLUTION2_H
#define CPP_0136_SOLUTION2_H
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int singleNumber(vector<int> &nums) {
int a = 0;
for (auto num: nums) {
a ^= num;
}
return a;
}
};
#endif //CPP_0136_SOLUTION2_H
|
ooooo-youwillsee/leetcode | 0441-Arranging-Coins/cpp_0441/Solution3.h | <filename>0441-Arranging-Coins/cpp_0441/Solution3.h
//
// Created by ooooo on 2020/1/19.
//
#ifndef CPP_0441__SOLUTION3_H_
#define CPP_0441__SOLUTION3_H_
#include <iostream>
#include <cmath>
using namespace std;
/**
* 数学公式求解 k(k+1) /2 = n ==> 其正数解为 k = sqrt(2n+1/4) - 1/2
*
* => k = sqrt(2) * sqrt(n + 1/8) - 1/2
*/
class Solution {
public:
int arrangeCoins(int n) {
return int(sqrt(2) * sqrt(n + 0.125) - 0.5);
}
};
#endif //CPP_0441__SOLUTION3_H_
|
ooooo-youwillsee/leetcode | 0092-Reverse Linked List II/cpp_0092/Solution1.h | <gh_stars>10-100
/**
* @author ooooo
* @date 2021/3/18 17:59
*/
#ifndef CPP_0092__SOLUTION1_H_
#define CPP_0092__SOLUTION1_H_
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode *reverse(ListNode *head, int cnt) {
ListNode *cur = head, *prev = nullptr;
while (cnt > 0) {
ListNode *next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
cnt--;
}
head->next = cur;
return prev;
}
ListNode *reverseBetween(ListNode *head, int left, int right) {
ListNode *dummyHead = new ListNode(-1);
dummyHead->next = head;
int cnt = 1;
ListNode *cur = dummyHead;
while (cnt < left) {
cur = cur->next;
cnt++;
}
ListNode *prev = cur;
prev->next = reverse(prev->next, right - left + 1);
return dummyHead->next;
}
};
#endif //CPP_0092__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 1576-Replace-All-XLetter-to-Avoid-Consecutive-Repeating-Characters/cpp_1576/Solution2.h | /**
* @author ooooo
* @date 2020/9/7 14:56
*/
#ifndef CPP_1576__SOLUTION2_H_
#define CPP_1576__SOLUTION2_H_
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string modifyString(string s) {
for (int i = 0; i < s.size(); ++i) {
if (s[i] != '?') continue;
char c = 'a';
for (int j = 0; j < 26; ++j) {
c += j;
if (((i > 0 && c != s[i - 1]) || i == 0) && ((i + 1 < s.size() && c != s[i + 1]) || i == s.size() - 1)) {
s[i] = c;
break;
}
}
}
return s;
}
};
#endif //CPP_1576__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0970-Powerful-Integers/cpp_0970/Solution1.h | //
// Created by ooooo on 2020/1/17.
//
#ifndef CPP_0970__SOLUTION1_H_
#define CPP_0970__SOLUTION1_H_
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
public:
int calcMaxBound(int x, int bound) {
if (x == 1) return bound;
int ans = 0, sum = 1;
while (sum <= bound) {
ans++;
sum *= x;
}
return ans;
}
vector<int> powerfulIntegers(int x, int y, int bound) {
unordered_set<int> ans;
for (int i = 0; i < calcMaxBound(x, bound); ++i) {
for (int j = 0; j < calcMaxBound(y, bound); ++j) {
int sum = pow(x, i) + pow(y, j);
if (sum <= bound) {
ans.insert(sum);
}
}
}
return vector<int>(ans.begin(), ans.end());
}
};
#endif //CPP_0970__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 1744-Can You Eat Your Favorite Candy on Your Favorite Day/cpp_1744/Solution1.h | /**
* @author ooooo
* @date 2021/6/1 14:17
*/
#ifndef CPP_1744__SOLUTION1_H_
#define CPP_1744__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
using LL = long long;
vector<bool> canEat(vector<int> &candiesCount, vector<vector<int>> &queries) {
int n = candiesCount.size();
LL preSum[n + 1];
memset(preSum, 0, sizeof(preSum));
for (int i = 0; i < n; i++) {
preSum[i + 1] = preSum[i] + candiesCount[i];
}
vector<bool> ans(queries.size());
for (int i = 0; i < queries.size(); i++) {
auto q = queries[i];
auto t = q[0], d = q[1] + 1, c = q[2];
ans[i] = preSum[t] < (long long) d * (long long) c && preSum[t + 1] >= d;
}
return ans;
}
};
#endif //CPP_1744__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0501-Find-Mode-in-Binary-Search-Tree/cpp_0501/Solution2.h | /**
* @author ooooo
* @date 2020/9/24 10:46
*/
#ifndef CPP_0501__SOLUTION2_H_
#define CPP_0501__SOLUTION2_H_
#include "TreeNode.h"
class Solution {
public:
unordered_map<int, int> m;
int c = 0; // 最高
void dfs(TreeNode *node) {
if (!node) return;
dfs(node->left);
m[node->val]++;
c = max(c, m[node->val]);
dfs(node->right);
}
vector<int> findMode(TreeNode *root) {
dfs(root);
vector<int> ans;
for (auto &[k, v]: m) {
if (c == v) {
ans.emplace_back(k);
}
}
return ans;
}
};
#endif //CPP_0501__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0283-Move-Zeroes/cpp_0283/Solution1.h | <gh_stars>10-100
//
// Created by ooooo on 2020/1/6.
//
#ifndef CPP_0283_SOLUTION1_H
#define CPP_0283_SOLUTION1_H
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int> &nums) {
if (nums.size() <= 1) return;
int i = 0, j = 0;
while (true) {
while (i < nums.size() && nums[i] != 0) i++;
while (j < nums.size() && nums[j] == 0) j++;
if (i > j) {
j++;
continue;
}
if (j >= nums.size() || i >= nums.size()) break;
swap(nums[i], nums[j]);
}
}
};
#endif //CPP_0283_SOLUTION1_H
|
ooooo-youwillsee/leetcode | lcof_041/cpp_041/Solution1.h | <reponame>ooooo-youwillsee/leetcode<filename>lcof_041/cpp_041/Solution1.h
//
// Created by ooooo on 2020/3/25.
//
#ifndef CPP_041__SOLUTION1_H_
#define CPP_041__SOLUTION1_H_
#include <iostream>
#include <queue>
using namespace std;
/**
* solution1 : AVL树,每个节点记录子节点个数
* solution2 : 最大堆 < 最小堆
*/
class MedianFinder {
private:
priority_queue<int, vector<int>, less<int>> max;
priority_queue<int, vector<int>, greater<int>> min;
public:
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
if (max.empty()) {
max.push(num);
return;
}
if (min.size() == max.size()) {
if (num > min.top()) {
max.push(min.top());
min.pop();
min.push(num);
} else {
max.push(num);
}
} else {
if (num >= max.top()) {
min.push(num);
} else {
min.push(max.top());
max.pop();
max.push(num);
}
}
}
double findMedian() {
if (min.size() == max.size()) {
return (min.top() + max.top()) / 2.0;
} else {
return max.top();
}
}
};
#endif //CPP_041__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0107-Binary-Tree-Level-Order-Traversal-II/cpp_0107/Solution1.h | <filename>0107-Binary-Tree-Level-Order-Traversal-II/cpp_0107/Solution1.h
//
// Created by ooooo on 2019/12/28.
//
#ifndef CPP_0107_SOLUTION1_H
#define CPP_0107_SOLUTION1_H
#include "TreeNode.h"
#include <stack>
#include <vector>
#include <queue>
class Solution {
private:
vector<vector<int>> levelOrder(TreeNode *root) {
vector<vector<int>> s;
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
vector<int> vec;
for (int i = 0, len = q.size(); i < len; ++i) {
TreeNode *node = q.front();
q.pop();
vec.push_back(node->val);
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
}
s.insert(begin(s), vec);
}
return s;
}
public:
vector<vector<int>> levelOrderBottom(TreeNode *root) {
if (!root) return {};
return levelOrder(root);
}
};
#endif //CPP_0107_SOLUTION1_H
|
ooooo-youwillsee/leetcode | lcof_032-1/cpp_032-1/Solution1.h | //
// Created by ooooo on 2020/3/20.
//
#ifndef CPP_032_1__SOLUTION1_H_
#define CPP_032_1__SOLUTION1_H_
#include "TreeNode.h"
#include <queue>
class Solution {
public:
vector<int> levelOrder(TreeNode *root) {
if (!root) return {};
vector<int> ans;
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
for (int i = 0, len = q.size(); i < len; ++i) {
auto node = q.front();
q.pop();
ans.emplace_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return ans;
}
};
#endif //CPP_032_1__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcof_059-1/cpp_059-1/Solution2.h | <gh_stars>10-100
//
// Created by ooooo on 2020/4/19.
//
#ifndef CPP_059_1__SOLUTION2_H_
#define CPP_059_1__SOLUTION2_H_
#include <iostream>
#include <deque>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> maxSlidingWindow(vector<int> &nums, int k) {
if (k == 0 && nums.empty()) return {};
vector<int> ans;
deque<int> q;
for (int i = 0, len = nums.size(); i < len; ++i) {
while (!q.empty() && q.front() <= i - k) q.pop_front();
while (!q.empty() && nums[q.back()] < nums[i]) q.pop_back();
q.push_back(i);
if (i >= k - 1) ans.push_back(nums[q.front()]);
}
return ans;
}
};
#endif //CPP_059_1__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0659-Split Array into Consecutive Subsequences/cpp_0659/Solution2.h | /**
* @author ooooo
* @date 2020/12/4 21:35
*/
#ifndef CPP_0659__SOLUTION2_H_
#define CPP_0659__SOLUTION2_H_
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool isPossible(vector<int> &nums) {
// key是以x结尾的子序列, value是子序列长度的最小堆
unordered_map<int, priority_queue<int, vector<int>, greater<int>>> m;
for (auto &x: nums) {
if (m.find(x - 1) != m.end()) {
auto min_len = m[x - 1].top();
m[x - 1].pop();
if (m[x - 1].empty()) {
m.erase(x - 1);
}
m[x].push(min_len + 1);
} else {
m[x].push(1);
}
}
for (auto &[k, v] :m) {
if (v.top() < 3) return false;
}
return true;
}
};
#endif //CPP_0659__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 1608-Special Array With X Elements Greater Than or Equal X/cpp_1608/Solution1.h | /**
* @author ooooo
* @date 2020/10/11 13:40
*/
#ifndef CPP_1608__SOLUTION1_H_
#define CPP_1608__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_set>
#include <queue>
using namespace std;
int specialArray(vector<int> &nums) {
sort(nums.begin(), nums.end());
for (int i = 1; i <= nums.size(); ++i) {
auto it = lower_bound(nums.begin(), nums.end(), i);
int x = nums.end() - it;
if (x == i) return x;
}
return -1;
}
#endif //CPP_1608__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0190-Reverse Bits/cpp_0190/Solution1.h | <gh_stars>10-100
/**
* @author ooooo
* @date 2021/3/29 16:35
*/
#ifndef CPP_0190__SOLUTION1_H_
#define CPP_0190__SOLUTION1_H_
#include <iostream>
using namespace std;
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t x = 0;
for (int i = 0; i < 32; i++) {
if (n & (1 << i)) {
x |= (1 << (31 - i));
}
}
return x;
}
};
#endif //CPP_0190__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0344-Reverse-String/cpp_0344/Solution1.h | <filename>0344-Reverse-String/cpp_0344/Solution1.h<gh_stars>10-100
//
// Created by ooooo on 2020/1/8.
//
#ifndef CPP_0344_SOLUTION1_H
#define CPP_0344_SOLUTION1_H
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void reverseString(vector<char> &s) {
if (s.size() <= 1) return;
for (int i = 0, j = s.size() - 1; i < j; ++i, --j) {
swap(s[i], s[j]);
}
}
};
#endif //CPP_0344_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0709-To-Lower-Case/cpp_0709/Solution1.h | //
// Created by ooooo on 2020/1/30.
//
#ifndef CPP_0709__SOLUTION1_H_
#define CPP_0709__SOLUTION1_H_
#include <iostream>
using namespace std;
class Solution {
public:
string toLowerCase(string str) {
for (int i = 0; i < str.size(); ++i) {
str[i] = tolower(str[i]);
}
return str;
}
};
#endif //CPP_0709__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcof_055-2/cpp_055-2/Solution2.h | <gh_stars>10-100
//
// Created by ooooo on 2020/4/11.
//
#ifndef CPP_055_2__SOLUTION2_H_
#define CPP_055_2__SOLUTION2_H_
#include "TreeNode.h"
#include <math.h>
#include <unordered_map>
/**
* 后序遍历
*/
class Solution {
public:
bool isBalanced(TreeNode *node, int &depth) {
if (!node) {
depth = 0;
return true;
}
int left = 0, right = 0;
if (isBalanced(node->left, left) && isBalanced(node->right, right)) {
if (abs(left - right) <= 1) {
depth = max(left, right) + 1;
return true;
}
}
return false;
}
bool isBalanced(TreeNode *root) {
if (!root) return true;
int depth = 0;
return isBalanced(root, depth);
}
};
#endif //CPP_055_2__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0637-Average-of-Levels-in-Binary-Tree/cpp_0637/Solution1.h | //
// Created by ooooo on 2020/1/3.
//
#ifndef CPP_0637_SOLUTION1_H
#define CPP_0637_SOLUTION1_H
#include "TreeNode.h"
#include <queue>
#include <vector>
class Solution {
public:
vector<double> averageOfLevels(TreeNode *root) {
if (!root) return {};
vector<double> res;
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
int size = q.size(), count = q.size();
double sum = 0;
while (size--) {
TreeNode *node = q.front();
q.pop();
sum += node->val;
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
res.push_back(sum / count);
}
return res;
}
};
#endif //CPP_0637_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0538-Convert-BST-to_Greater-Tree/cpp_0538/Solution2.h | //
// Created by ooooo on 2020/1/3.
//
#ifndef CPP_0538_SOLUTION2_H
#define CPP_0538_SOLUTION2_H
#include "TreeNode.h"
class Solution {
public:
int sum = 0;
void inOrder(TreeNode *node) {
if (!node) return;
inOrder(node->right);
node->val += sum;
sum = node->val;
inOrder(node->left);
}
// 最快。。
TreeNode *convertBST2(TreeNode *root) {
sum = 0;
inOrder(root);
return root;
}
TreeNode *convertBST(TreeNode *root) {
if (!root) return nullptr;
convertBST(root->right);
root->val += sum;
sum = root->val;
convertBST(root->left);
return root;
}
};
#endif //CPP_0538_SOLUTION2_H
|
ooooo-youwillsee/leetcode | 0268-Missing-Number/cpp_0268/Solution1.h | <filename>0268-Missing-Number/cpp_0268/Solution1.h
//
// Created by ooooo on 2020/1/6.
//
#ifndef CPP_0268_SOLUTION1_H
#define CPP_0268_SOLUTION1_H
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
int missingNumber(vector<int> &nums) {
if (nums.empty()) return 0;
unordered_set<int> s;
for (int i = 0, len = nums.size(); i <= len; ++i) {
s.insert(i);
}
for (auto &num: nums) {
if (s.count(num)) s.erase(num);
}
return *begin(s);
}
};
#endif //CPP_0268_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0033-Search-in-Rotated-Sorted-Array/cpp_0033/Solution1.h | //
// Created by ooooo on 2020/2/9.
//
#ifndef CPP_0033__SOLUTION1_H_
#define CPP_0033__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* 二分法 (一次)
*/
class Solution {
public:
int search(vector<int> &nums, int target) {
if (nums.empty()) return -1;
int left = 0, right = nums.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
if (nums[left] < nums[mid]) {
// 左边升序
if (target <= nums[mid] && target >= nums[left]) {
right = mid - 1;
} else {
left = mid;
}
} else if (nums[left] > nums[mid]) {
// 右边升序
if (target <= nums[right] && target >= nums[mid]) {
left = mid + 1;
} else {
right = mid;
}
} else {
// mid == left
left = mid + 1;
}
}
return nums[left] == target ? left : -1;
}
};
#endif //CPP_0033__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0136-Single-Number/cpp_0136/Solution1.h | <reponame>ooooo-youwillsee/leetcode
//
// Created by ooooo on 2019/12/30.
//
#ifndef CPP_0136_SOLUTION1_H
#define CPP_0136_SOLUTION1_H
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
int singleNumber(vector<int> &nums) {
unordered_map<int, int> map;
for (auto num : nums) {
if (map.find(num) == map.end()) {
map[num] = 1;
} else {
map[num] += 1;
}
}
for (auto item : map) {
if (item.second == 1) {
return item.first;
}
}
return 0;
}
};
#endif //CPP_0136_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0074-Search a 2D Matrix/cpp_0074/Solution1.h | /**
* @author ooooo
* @date 2021/3/30 16:09
*/
#ifndef CPP_0074__SOLUTION1_H_
#define CPP_0074__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size(), n = matrix[0].size();
int i = 0, j = n-1;
while (i >= 0 && i < m && j >=0 && j < n) {
if (matrix[i][j] < target) {
i++;
}else if (matrix[i][j] > target) {
j--;
}else {
return true;
}
}
return false;
}
};
#endif //CPP_0074__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0068-Text Justification/cpp_0068/Solution1.h | /**
* @author ooooo
* @date 2021/2/13 14:48
*/
#ifndef CPP_0068__SOLUTION1_H_
#define CPP_0068__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
string convert(vector<string> &words, int maxWidth, int lastI, int i, bool lastLine) {
int spaceCount = maxWidth;
int wordCount = i - lastI + 1;
int suffixSpaceCount = 1; // 默认为一个空格
for (int j = lastI; j <= i; ++j) {
spaceCount -= words[j].size();
}
spaceCount -= (wordCount - 1);
// 可能只有一个单词
int spaceAvg = wordCount != 1 ? spaceCount / (wordCount - 1) : 0;
int spaceExtra = 0;
if (wordCount != 1 && spaceCount % (wordCount - 1) != 0) {
spaceExtra = spaceCount % (wordCount - 1);
}
string line = "";
for (int j = lastI, k = 0; j <= i - 1; ++j, k++) {
line += words[j];
fill_n(back_inserter(line), suffixSpaceCount + spaceAvg + (k < spaceExtra), ' ');
}
line += words[i];
fill_n(back_inserter(line), maxWidth - line.size(), ' ');
return line;
}
vector<string> fullJustify(vector<string> &words, int maxWidth) {
int sz = words.size();
int wordCount = 0;
vector<string> ans;
for (int i = 0, lastI = 0; i < sz; ++i) {
// 一个单词最少一个空格
wordCount += words[i].size() + 1;
if (i + 1 < sz && wordCount + words[i + 1].size() > maxWidth) {
ans.emplace_back(convert(words, maxWidth, lastI, i, i == sz - 1));
wordCount = 0;
lastI = i + 1;
} else if (i == sz - 1) {
ans.emplace_back(getLastLine(maxWidth, i, lastI, words));
}
}
return ans;
}
string getLastLine(int maxWidth, int i, int lastI, vector<string> &words) const {
string line = "";
for (int k = lastI; k <= i; ++k) {
line += words[k];
if (k != i) line += " ";
}
fill_n(back_inserter(line), maxWidth - line.size(), ' ');
return line;
}
};
#endif //CPP_0068__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcp-18/cpp_018/Solution2.h | <gh_stars>10-100
/**
* @author ooooo
* @date 2020/9/27 11:23
*/
#ifndef CPP_018__SOLUTION2_H_
#define CPP_018__SOLUTION2_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int breakfastNumber(vector<int> &staple, vector<int> &drinks, int x) {
vector<int> prices(x + 1, 0);
int ans = 0;
for (auto &item: staple) {
if (item < x) prices[item]++;
}
// prices[i] 表示 小于i价格的个数
for (int i = 2; i < x + 1; ++i) {
prices[i] += prices[i - 1];
}
for (int i = 0; i < drinks.size(); ++i) {
int y = x - drinks[i];
if (y > 0) ans = (ans + prices[y]) % 1000000007;
}
return ans;
}
};
#endif //CPP_018__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0518-Coin Change 2/cpp_0518/Solution2.h | /**
* @author ooooo
* @date 2021/2/17 19:22
*/
#ifndef CPP_0518__SOLUTION2_H_
#define CPP_0518__SOLUTION2_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int dfs(int amount, vector<int> &coins, int i) {
if (visited[amount][i]) {
return memo[amount][i];
}
if (amount == 0) {
return 1;
}
int ans = 0;
for (int j = i; j < coins.size(); ++j) {
if (amount - coins[j] >= 0) {
ans += dfs(amount - coins[j], coins, j);
}
}
memo[amount][i] = ans;
visited[amount][i] = true;
return ans;
}
unordered_map<int, unordered_map<int, int>> memo;
unordered_map<int, unordered_map<int, bool>> visited;
int change(int amount, vector<int> &coins) {
sort(coins.begin(), coins.end());
memo.clear();
visited.clear();
return dfs(amount, coins, 0);
}
};
#endif //CPP_0518__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 1759-Count Number of Homogenous Substrings/cpp_1759/Solution1.h | <gh_stars>10-100
/**
* @author ooooo
* @date 2021/2/21 19:07
*/
#ifndef CPP_1759__SOLUTION1_H_
#define CPP_1759__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
static const long MOD = 1000000007;
int countHomogenous(string s) {
s += "#";
int n = s.size();
long long cnt = 1;
long long ans = 0;
for (int r = 1; r < n; ++r) {
if (s[r] == s[r - 1]) {
cnt++;
} else {
ans = (ans + (1 + cnt) * cnt / 2) % MOD;
cnt = 1;
}
}
return ans;
}
};
#endif //CPP_1759__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0125-Valid-Palindrome/cpp_0125/Solution2.h | //
// Created by ooooo on 2020/1/7.
//
#ifndef CPP_0125_SOLUTION2_H
#define CPP_0125_SOLUTION2_H
#include <iostream>
using namespace std;
class Solution {
public:
bool isPalindrome(string s) {
string ans = "";
for (auto &c: s) {
if (isalnum(c)) ans += tolower(c);
}
string source = ans;
reverse(ans.begin(), ans.end());
return source == ans;
}
};
#endif //CPP_0125_SOLUTION2_H
|
ooooo-youwillsee/leetcode | 1818-Minimum Absolute Sum Difference/cpp_1818/Solution1.h | /**
* @author ooooo
* @date 2021/4/11 15:56
*/
#ifndef CPP_1818__SOLUTION1_H_
#define CPP_1818__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <stack>
#include <numeric>
#include <queue>
using namespace std;
class Solution {
public:
int minAbsoluteSumDiff(vector<int> nums1, vector<int> nums2) {
int n = nums1.size();
vector<long long> pre(n + 1);
for (int i = 0; i < n; ++i) {
pre[i + 1] = pre[i] + abs(nums1[i] - nums2[i]);
}
long long ans = pre[n];
if (ans == 0) {
return 0;
}
int mod = 1e9 + 7;
sort(nums1.begin(), nums1.end());
for (int i = 0; i < n; ++i) {
long long t = (pre[i] + pre[n] - pre[i + 1]) % mod;
auto it = lower_bound(nums1.begin(), nums1.end(), nums2[i]);
if (it == nums1.end()) {
it = nums1.end() - 1;
}
ans = min(t + abs(*it - nums2[i]), ans);
if (it - 1 >= nums1.begin()) {
ans = min(t + abs(*(it - 1) - nums2[i]), ans);
}
if (it + 1 < nums1.end()) {
ans = min(t + abs(*(it + 1) - nums2[i]), ans);
}
}
return ans % mod;
}
};
#endif //CPP_1818__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0746-Min-Cost-Climbing-Stairs/cpp_0746/Solution2.h | //
// Created by ooooo on 2020/2/5.
//
#ifndef CPP_0746__SOLUTION2_H_
#define CPP_0746__SOLUTION2_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* dp[i] = min(dp[i-1] , dp[i-2]) + p
*/
class Solution {
public:
int minCostClimbingStairs(vector<int> &cost) {
int n = cost.size(), *dp = new int[n];
dp[0] = cost[0], dp[1] = cost[1];
for (int i = 2; i < n; ++i) {
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i];
}
// 倒数第二个可以直接跳两步
return min(dp[n - 1], dp[n - 2]);
}
};
#endif //CPP_0746__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 1031-Maximum Sum of Two Non-Overlapping Subarrays/cpp_1031/SolutIon2.h | <reponame>ooooo-youwillsee/leetcode<gh_stars>10-100
/**
* @author ooooo
* @date 2021/2/15 17:56
*/
#ifndef CPP_1031__SOLUTION2_H_
#define CPP_1031__SOLUTION2_H_
#include <vector>
using namespace std;
class Solution {
public:
vector<int> preSum;
int maxSum(vector<int> &A, int L, int M) {
int n = A.size();
// dp[i][0] 表示前L个连续的子数组最大和
// dp[i][1] 表示后M个连续的子数组最大和
vector<vector<int>> dp(n, vector<int>(2));
int sum = preSum[L];
dp[L - 1][0] = sum;
for (int i = L; i < n; ++i) {
sum = max(sum, preSum[i + 1] - preSum[i - L + 1]);
dp[i][0] = sum;
}
sum = preSum[n] - preSum[n - M];
dp[n - M][1] = sum;
for (int i = n - M - 1; i >= 0; --i) {
sum = max(sum, preSum[i + M] - preSum[i]);
dp[i][1] = sum;
}
int ans = 0;
for (int i = L - 1; i < n - M; ++i) {
ans = max(ans, dp[i][0] + dp[i + 1][1]);
}
return ans;
}
int maxSumTwoNoOverlap(vector<int> &A, int L, int M) {
preSum.assign(A.size() + 1, 0);
for (int i = 0; i < A.size(); ++i) {
preSum[i + 1] = preSum[i] + A[i];
}
// 两种情况
return max(maxSum(A, L, M), maxSum(A, M, L));
}
};
#endif //CPP_1031__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 1624-Largest Substring Between Two Equal Characters/cpp_1624/Solution1.h | <gh_stars>10-100
/**
* @author ooooo
* @date 2020/11/15 09:01
*/
#ifndef CPP_1624__SOLUTION1_H_
#define CPP_1624__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <stack>
#include <numeric>
using namespace std;
class Solution {
public:
int maxLengthBetweenEqualCharacters(string s) {
int ans = -1;
for (int i = 0; i < s.size(); ++i) {
for (int j = s.size() - 1; j >= i; --j) {
if (s[j] == s[i] && j != i) {
ans = max(ans, j - i - 1);
break;
}
}
}
return ans;
}
}
#endif //CPP_1624__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0035-Search-Insert-Position/cpp_0035/Solution1.h | //
// Created by ooooo on 2020/1/6.
//
#ifndef CPP_0035_SOLUTION1_H
#define CPP_0035_SOLUTION1_H
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int searchInsert(vector<int> &nums, int target) {
if (nums.empty() || target < nums[0]) return 0;
if (target > nums[nums.size() - 1]) return nums.size();
int ans = -1;
for (int i = 0; i < nums.size() - 1; ++i) {
if (nums[i] == target) {
ans = i;
break;
} else if (target > nums[i] && target < nums[i + 1]) {
ans = i + 1;
break;
}
}
return ans == -1 ? nums.size() - 1 : ans;
}
};
#endif //CPP_0035_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 1004-Max Consecutive Ones III/cpp_1004/Solution2.h | /**
* @author ooooo
* @date 2021/2/19 09:53
*/
#ifndef CPP_1004__SOLUTION2_H_
#define CPP_1004__SOLUTION2_H_
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
int longestOnes(vector<int> &A, int K) {
int n = A.size();
int ans = 0;
int l = 0, r = 0;
int cnt0 = 0;
while (r < n) {
if (A[r] == 0) {
cnt0++;
}
while (cnt0 > K) {
if (A[l] == 0) {
cnt0--;
}
l++;
}
ans = max(ans, r - l + 1);
r++;
}
return ans;
}
};
#endif //CPP_1004__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0993-Cousins-in-Binary-Tree/cpp_0993/Solution1.h | <gh_stars>10-100
//
// Created by ooooo on 2020/1/5.
//
#ifndef CPP_0993_SOLUTION1_H
#define CPP_0993_SOLUTION1_H
#include "TreeNode.h"
#include <queue>
/**
* bfs
*/
class Solution {
public:
bool isCousins(TreeNode *root, int x, int y) {
if (!root) return false;
queue<TreeNode *> q;
queue<TreeNode *> parents;
q.push(root);
parents.push(root);
while (!q.empty()) {
int size = q.size();
bool findX = false, findY = false;
TreeNode *xParent = nullptr, *yParent = nullptr;
while (size--) {
TreeNode *node = q.front();
q.pop();
TreeNode *parent = parents.front();
parents.pop();
if (node->val == x) {
findX = true;
xParent = parent;
}
if (node->val == y) {
findY = true;
yParent = parent;
}
if (node->left) {
q.push(node->left);
parents.push(node);
}
if (node->right) {
q.push(node->right);
parents.push(node);
}
}
if (findX != findY) return false;
if (findX) return xParent != yParent;
}
return false;
}
};
#endif //CPP_0993_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 1577-Number-of-Ways-Where-Square-of-Number-Is-Equal-to-Product-of-Two-Numbers/cpp_1577/Solution2.h | /**
* @author ooooo
* @date 2020/9/7 15:17
*/
#ifndef CPP_1577__SOLUTION2_H_
#define CPP_1577__SOLUTION2_H_
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution1 {
public:
int numTriplets(vector<int> &nums1, vector<int> &nums2) {
int count = 0;
unordered_map<long long, int> m1;
for (int j = 0; j < nums1.size(); ++j) {
for (int k = j + 1; k < nums1.size(); ++k) {
m1[(long long) nums1[j] * (long long) nums1[k]]++;
}
}
unordered_map<long long, int> m2;
for (int j = 0; j < nums2.size(); ++j) {
for (int k = j + 1; k < nums2.size(); ++k) {
m2[(long long) nums2[j] * (long long) nums2[k]]++;
}
}
for (int i = 0; i < nums1.size(); ++i) {
long long sum = (long long) nums1[i] * (long long) nums1[i];
count += m2[sum];
}
for (int i = 0; i < nums2.size(); ++i) {
long long sum = (long long) nums2[i] * (long long) nums2[i];
count += m1[sum];
}
return count;
}
};
#endif //CPP_1577__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0207-Course-Schedule/cpp_0207/Solution1.h | //
// Created by ooooo on 2020/2/19.
//
#ifndef CPP_0207__SOLUTION1_H_
#define CPP_0207__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* dfs + 邻接矩阵
*/
class Solution {
public:
vector<vector<bool>> graph;
// 1 表示已访问, -1 表示在上次 dfs 中已经访问过,说明这个节点没有问题, 0 表示没有访问过
vector<int> mark;
int n;
bool dfs(int i) {
if (mark[i] == -1) return true;
if (mark[i] == 1) return false;
mark[i] = 1;
for (int j = 0; j < n; ++j) {
if (graph[i][j] && !dfs(j)) return false;
}
mark[i] = -1;
return true;
}
bool canFinish(int numCourses, vector<vector<int>> &prerequisites) {
n = numCourses;
graph.assign(n, vector<bool>(n, false));
mark.assign(n, 0);
for (auto &vec: prerequisites) {
graph[vec[0]][vec[1]] = true;
}
for (int i = 0; i < numCourses; ++i) {
if (!dfs(i)) return false;
}
return true;
}
};
#endif //CPP_0207__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 1720-Decode XORed Array/cpp_1720/Solution1.h | /**
* @author ooooo
* @date 2021/1/20 12:18
*/
#ifndef CPP_1720__SOLUTION1_H_
#define CPP_1720__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <stack>
using namespace std;
class Solution {
public:
vector<int> decode(vector<int> &encoded, int first) {
vector<int> ans = {first};
for (int i = 0; i < encoded.size(); ++i) {
ans.push_back(abs(encoded[i] ^ ans.back()));
}
return ans;
}
};
#endif //CPP_1720__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcof_046/cpp_046/Solution1.h | //
// Created by ooooo on 2020/4/2.
//
#ifndef CPP_046__SOLUTION1_H_
#define CPP_046__SOLUTION1_H_
#include <iostream>
#include <unordered_map>
using namespace std;
class Solution {
public:
int valid(int i) {
if (i + 1 >= s.size() || s[i] == '0' || s[i] > '2') return false;
if (s[i] == '1') return true;
return s[i] == '2' && s[i + 1] < '6';
}
int dfs(int i) {
if (m.count(i)) return m[i];
if (i == s.size()) return 1;
if (i > s.size()) return 0;
int ans = dfs(i + 1);
if (valid(i)) {
ans += dfs(i + 2);
}
return m[i] = ans;
}
string s;
unordered_map<int, int> m;
int translateNum(int num) {
this->s = to_string(num);
return dfs(0);
}
};
#endif //CPP_046__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 1024-Video Stitching/cpp_1024/Solution1.h | /**
* @author ooooo
* @date 2020/10/24 09:55
*/
#ifndef CPP_1024__SOLUTION1_H_
#define CPP_1024__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* dp[i][j] 表示i到j区间的最小数目
*/
class Solution {
public:
int videoStitching(vector<vector<int>> &clips, int T) {
vector<vector<int>> dp(T + 1, vector<int>(T + 1));
for (int i = T - 1; i >= 0; --i) {
for (int j = i + 1; j <= T; ++j) {
dp[i][j] = clips.size() + 1;
for (int k = 0; k < clips.size(); ++k) {
int l = clips[k][0], r = clips[k][1];
if (r <= i || j <= l) continue;
if (l <= i && j <= r) {
dp[i][j] = 1;
} else if (r <= j) {
// 以最优解去计算
dp[i][j] = min(dp[i][j], dp[i][r] + dp[r][j]);
} else {
// 以最优解去计算
dp[i][j] = min(dp[i][j], dp[i][l] + dp[l][j]);
}
//cout << "i:" << i << " j:" << j << " ->" << dp[i][j] << " " << endl;
}
cout << "finally i:" << i << " j:" << j << " ->" << dp[i][j] << " " << endl;
}
}
return dp[0][T] > clips.size() ? -1 : dp[0][T];
}
};
#endif //CPP_1024__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0383-Ransom-Note/cpp_0383/Solution1.h | //
// Created by ooooo on 2020/1/25.
//
#ifndef CPP_0383__SOLUTION1_H_
#define CPP_0383__SOLUTION1_H_
#include <iostream>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> m1, m2;
for (auto c: ransomNote) {
++m1[c];
}
for (auto c: magazine) {
++m2[c];
}
for (auto entry: m1) {
if (m2[entry.first] < entry.second) return false;
}
return true;
}
};
#endif //CPP_0383__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 1705-Maximum Number of Eaten Apples/cpp_1705/Solution1.h | /**
* @author ooooo
* @date 2021/1/24 17:17
*/
#ifndef CPP_1705__SOLUTION1_H_
#define CPP_1705__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
int eatenApples(vector<int> &apples, vector<int> &days) {
int n = apples.size();
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
int ans = 0;
for (int i = 0; i < n; ++i) {
// 天数包括当天
q.push(make_pair(i + days[i] - 1, apples[i]));
while (!q.empty()) {
pair<int, int> x = q.top();
q.pop();
if (i <= x.first) {
ans++;
// 吃掉一个,个数减一
x.second--;
// 如果还有,重新添加到优先队列
if (x.second > 0) {
q.push(x);
}
break;
}
}
}
int i = n;
while (true) {
while (!q.empty()) {
pair<int, int> x = q.top();
q.pop();
if (i <= x.first) {
ans++;
// 吃掉一个,个数减一
x.second--;
// 如果还有,重新添加到优先队列
if (x.second > 0) {
q.push(x);
}
break;
}
}
if (q.empty()) break;
i++;
}
return ans;
}
};
#endif //CPP_1705__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0338-Counting Bits/cpp_0338/Solution2.h | //
// Created by ooooo on 2019/12/5.
//
#ifndef CPP_0338_SOLUTION2_H
#define CPP_0338_SOLUTION2_H
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res = vector<int>(num + 1, 0);
for (int i = 1; i <= num; i++) {
res[i] = res[i & i - 1] + 1;
}
return res;
}
};
#endif //CPP_0338_SOLUTION2_H
|
ooooo-youwillsee/leetcode | 0475-Heaters/cpp_0475/Solution1.h | <gh_stars>10-100
//
// Created by ooooo on 2020/1/19.
//
#ifndef CPP_0475__SOLUTION1_H_
#define CPP_0475__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int findRadius(vector<int> &houses, vector<int> &heaters) {
vector<int> ans;
sort(houses.begin(), houses.end());
sort(heaters.begin(), heaters.end());
for (auto house : houses) {
int left = 0, right = heaters.size() - 1, mid;
while (left < right) {
mid = left + (right - left) / 2;
if (heaters[mid] < house) {
left = mid + 1;
} else {
right = mid;
}
}
// heaters中的最大值已经小于house,最大距离肯定有 house - heaters[left]
if (heaters[left] < house) {
ans.push_back(house - heaters[left]);
} else if (left) {
ans.push_back(min(heaters[left] - house, house - heaters[left - 1]));
} else {
ans.push_back(heaters[left] - house);
}
}
int res = 0;
for_each(ans.begin(), ans.end(), [&res](auto x) { res = max(res, x); });
return res;
}
};
#endif //CPP_0475__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0039-Combination-Sum/cpp_0039/Solution1.h | //
// Created by ooooo on 2020/2/10.
//
#ifndef CPP_0039__SOLUTION1_H_
#define CPP_0039__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <set>
#include <unordered_set>
using namespace std;
/**
* vector#push_back() 会复制数据
*
* 允许重复数字 --> i可以再次取到,利用排序保证结果不重复
*/
class Solution {
public:
void help(vector<int> nums, vector<int> &candidates, int start, int target) {
if (target == 0) {
ans.push_back(nums);
return;
}
for (int i = start; i < candidates.size() && target - candidates[i] >= 0; ++i) {
auto num = candidates[i];
nums.push_back(num);
help(nums, candidates, i, target - num);
nums.pop_back();
}
}
vector<vector<int>> ans;
vector<vector<int>> combinationSum(vector<int> &candidates, int target) {
sort(candidates.begin(), candidates.end());
help(vector<int>(), candidates, 0, target);
return ans;
}
};
#endif //CPP_0039__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0395-Longest Substring with At Least K Repeating Characters/cpp_0395/Solution1.h | <reponame>ooooo-youwillsee/leetcode<filename>0395-Longest Substring with At Least K Repeating Characters/cpp_0395/Solution1.h
/**
* @author ooooo
* @date 2021/2/27 10:57
*/
#ifndef CPP_0395__SOLUTION1_H_
#define CPP_0395__SOLUTION1_H_
#include <vector>
#include <iostream>
#include <unordered_map>
using namespace std;
// 滑动窗口
class Solution {
public:
int longestSubstring(string s, int k) {
int n = s.size();
int ans = 0;
// 对每一个字符种类进行遍历
for (int i = 1; i <= 26; ++i) {
int cnt = 0;
int l = 0, r = 0;
int less = 0;
vector<int> m(26, 0);
while (r < n) {
m[s[r] - 'a']++;
if (m[s[r] - 'a'] == 1) {
cnt++; // 字符种类数+1
less++; // 没满足条件的+1
}
if (m[s[r] - 'a'] == k) {
less--;
}
while (cnt > i) {
m[s[l] - 'a']--;
if (m[s[l] - 'a'] == 0) {
cnt--;
less--; // 没有该字符,不需要满足条件
}
if (m[s[l] - 'a'] == k - 1) {
// 又不满足条件了
less++;
}
l++;
}
if (less == 0) {
ans = max(ans, r - l + 1);
}
r++;
}
}
return ans;
}
};
#endif //CPP_0395__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0079-Word-Search/cpp_0079/Solution2.h | /**
* @author ooooo
* @date 2020/9/13 09:34
*/
#ifndef CPP_0079__SOLUTION2_H_
#define CPP_0079__SOLUTION2_H_
#include <vector>
#include <iostream>
using namespace std;
class Solution2 {
public:
vector<vector<char>> board;
vector<vector<bool>> visited;
vector<vector<int>> dx_dy = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int m = 0, n = 0;
bool inArea(int i, int j) {
return i < m && i >= 0 && j < n && j >= 0;
}
bool dfs(int i, int j, string &word, int k) {
visited[i][j] = true;
if (board[i][j] != word[k]) return visited[i][j] = false;
if (k == word.size() - 1) return true;
for (int p = 0; p < dx_dy.size(); ++p) {
int ni = i + dx_dy[p][0];
int nj = j + dx_dy[p][1];
if (!inArea(ni, nj) || visited[ni][nj]) continue;
if (dfs(ni, nj, word, k + 1)) return true;
}
return visited[i][j] = false;
}
bool exist(vector<vector<char>> &board, string word) {
this->board = board;
this->m = board.size();
this->n = board[0].size();
this->visited = vector<vector<bool>>(m, vector<bool>(n, false));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (dfs(i, j, word, 0)) return true;
}
}
return false;
}
};
#endif //CPP_0079__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0876-Middle-of-the-Linked-List/cpp_0876/Solution1.h | <gh_stars>10-100
//
// Created by ooooo on 2020/1/23.
//
#ifndef CPP_0876__SOLUTION1_H_
#define CPP_0876__SOLUTION1_H_
#include "ListNode.h"
/**
* 快慢指针
*/
class Solution {
public:
ListNode *middleNode(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};
#endif //CPP_0876__SOLUTION1_H_
|
Subsets and Splits