[LeetCode]刷题记录2
introduction
十月一号了,国庆快乐,题不能停
algorithm
没更新的日子里也没有偷懒,剑指offer的有些题太简单了
剑指offer II 23
12/27
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == nullptr || headB == nullptr) return nullptr;
ListNode *pA = headA, *pB = headB;
while (pA != pB)
{
if (pA) pA = pA->next;
else pA = headB;
if (pB) pB = pB->next;
else pB = headA;
}
return pA;
}
};
328. 奇偶链表
12/18
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head)return nullptr;
deque<ListNode*> dq_head,dq_tail;
ListNode *p = head;
while(p){
if(p)dq_head.push_back(p);
p = p -> next;
if(p)dq_tail.push_back(p);
if(p)p = p -> next;
}
while(!dq_head.empty()){
p = dq_head.front();
dq_head.pop_front();
if(!dq_head.empty())p -> next = dq_head.front();
}
p -> next = dq_tail.front();
while(!dq_tail.empty()){
p = dq_tail.front();
dq_tail.pop_front();
if(!dq_tail.empty())p -> next = dq_tail.front();
}
p -> next = nullptr;
return head;
}
};
445. 两数相加
12/17
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<ListNode*> st1;
stack<ListNode*> st2;
ListNode *p = l1,*q = l2;
while(l1){
st1.push(l1);
l1 = l1 -> next;
}
while(l2){
st2.push(l2);
l2 = l2 -> next;
}
int flag = st1.size() > st2.size() ? 1 : 0;
int ca = 0;
while(!st1.empty() || !st2.empty()){
int a = st1.empty() ? 0 : st1.top()->val;
int b = st2.empty() ? 0 : st2.top()->val;
int res = a + b + ca;
ca = res / 10 ;
int b_2 = res % 10 ;
if(flag)st1.top()->val = b_2;
else st2.top()->val = b_2;
if(!st1.empty())st1.pop();
if(!st2.empty())st2.pop();
}
if(ca != 0){
ListNode *hh = new ListNode(ca);
if(flag){
hh -> next = p;
p = hh;
}
else {
hh -> next =q;
q = hh;
}
}
return flag == 1 ? p : q;
}
};
725. 分隔链表
12/16
class Solution {
public:
vector<ListNode*> splitListToParts(ListNode* head, int k) {
vector<ListNode*> res(k,nullptr);
deque<ListNode*> qu;
ListNode *p = head;
while(p){
qu.push_back(p);
p = p -> next;
}
int size = qu.size();
int per = size / k ,ready = 0, kk = 0;
ListNode *end = nullptr;
while(!qu.empty()){
res[kk] = qu.front();
end = qu.front();
++kk;
for(int i = 0 ; i < per ; ++i){
++ready;
end = qu.front();
qu.pop_front();
}
if(ready + (k - kk) * per < size ){
++ready;
end = qu.front();
qu.pop_front();
}
end -> next = nullptr;
}
return res;
}
};
86. 分隔链表
12/15
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode *small = new ListNode();
ListNode *large = new ListNode();
ListNode *s_head = small,*l_head = large;
while(head){
if(head->val < x){
small->next = head;
small = small->next;
}else{
large->next = head;
large = large->next;
}
head = head->next;
}
large -> next = nullptr;
small->next = l_head -> next;
return s_head->next;
}
};
61. 旋转链表
12/14
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head)return nullptr;
deque<ListNode*> dq;
ListNode *p = head;
while(p->next){
dq.push_back(p);
p = p -> next;
}
dq.push_back(p);
p->next =head;
k %= dq.size();
while(k--){
dq.push_front(dq.back());
dq.pop_back();
}
head = dq.front();
dq.back()->next = nullptr;
return head;
}
};
817. 链表组件
12/13
class Solution {
public:
int numComponents(ListNode* head, vector<int>& nums) {
vector<bool> exists(10000,false);
for (int num : nums)exists[num] = true;
int res = 0;
ListNode* curr = head;
while (curr != nullptr)
{
if (exists[curr->val] && (curr->next == nullptr || !exists[curr->next->val]))
{
++res;
}
curr = curr->next;
}
return res;
}
};
剑指offer || 28
12/12
class Solution {
public:
Node* flatten(Node* head) {
dfs(head);
return head;
}
Node* dfs(Node *head){
Node *p = head,*tail = nullptr;
while(p){
Node *next = p->next;
if(p->child){
Node *child = p->child;
Node *child_tail = dfs(child);
p->child = nullptr;
p->next = child;
child->prev = p;
child_tail->next = next;
if(next)next->prev = child_tail;
tail = child_tail;
}else{
tail = p;
}
p = p->next;
}
return tail;
}
};
剑指offer || 78
12/11
class Solution {
public:
ListNode* merge(ListNode* left,ListNode* right){
ListNode *res = new ListNode(0);
ListNode *p=left,*q=right,*tmp=res;
while(p && q){
if(p->val <= q->val){
tmp->next = p;
p = p->next;
tmp = tmp->next;
}else{
tmp->next = q;
q = q->next;
tmp = tmp->next;
}
}
if(p)tmp->next = p;
if(q)tmp->next = q;
return res->next;
}
ListNode* merge_lists(vector<ListNode*>& lists,int st,int end) {
if(st == end)return lists[st];
int mid = st + ((end - st)>>1);
ListNode *sr1 = merge_lists(lists,st,mid);
ListNode *sr2 = merge_lists(lists,mid+1,end);
return merge(sr1,sr2);
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() == 0)return nullptr;
return merge_lists(lists,0,lists.size()-1);
}
};
剑指offer || 27 回文链表
12/11
随手写
class Solution {
public:
bool isPalindrome(ListNode* head) {
deque<ListNode*> dq;
ListNode *p = head;
while(p){
dq.push_back(p);
p = p->next;
}
while(!dq.empty()){
if(dq.front()->val == dq.back()->val){
if(dq.size()==1){
dq.pop_front();
}else{
dq.pop_front();
dq.pop_back();
}
}else{
return false;
}
}
return true;
}
};
剑指offer || 26
思路没毛病,一个野指针找了好久,曹了
12/10
class Solution {
public:
void reorderList(ListNode* head) {
if(!head->next)return;
deque<ListNode*> L,R;
ListNode *left=head,*right=head,*mid = head;
while(right && right->next){
mid = left;
left = left->next;
right = right->next->next;
}
mid->next = nullptr;
right = head;
while(right){
L.push_back(right);right = right->next;
}
while(left){
R.push_front(left);left = left->next;
}
right = L.front();
L.pop_front();
while(true){
if(R.empty() && L.empty())break;
if(!R.empty()){
R.front()->next = nullptr;
right->next = R.front();
R.pop_front();
right = right->next;
}
if(!L.empty()){
L.front()->next = nullptr;
right->next = L.front();
L.pop_front();
right = right->next;
}
}
}
};
剑指offer II 77
一个简单的没有错误的错误找了好久
12/9
class Solution {
public:
ListNode* merge_sort(ListNode *l1,ListNode *l2){
ListNode *head = new ListNode();
ListNode *node = head;
while(l1 && l2){
if(l1->val < l2->val){
node->next = l1;
l1 = l1->next;
}else{
node->next = l2;
l2 = l2->next;
}
node = node->next;
}
node->next = (l1 == nullptr) ? l2 : l1;
return head->next;
}
ListNode* sortList(ListNode* head) {
if(!head || !head->next )return head;
ListNode *pre = head,*low = head,*fast=head;
while(fast && fast->next){
pre = low;
low = low->next;
fast = fast->next->next;
}
pre->next = nullptr;
return merge_sort(sortList(head), sortList(low));
}
};
1669 合并两个链表
与链表有关的要全部刷完,很简单
12/8
class Solution {
public:
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
ListNode* left = list1,*right = list1,*p=list2;
int k=a-1;
while(k--)left = left->next;
while(b--)right = right->next;
while(p->next != nullptr)p = p->next;
left->next = list2;
p->next = right->next;
return list1;
}
};
剑指offer II 21 删除倒数第k个节点
12/7
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head->next == nullptr)return nullptr;
ListNode* fast=head,*low = head,*tmp=head;
while(n--)fast = fast->next;
if(!fast)return head->next;
while(fast){
fast = fast->next;
tmp=low;
low = low ->next;
}
tmp->next = low->next;
return head;
}
};
2095 删除链表中的中间节点
2021/12/7
一搞linux 就忘记了,以后专注链表 排序 嵌入式算法
class Solution {
public:
ListNode* deleteMiddle(ListNode* head) {
if(head->next == nullptr)return nullptr;
ListNode* fast = head,*low = head,*pre = head;
while(fast->next){
if(fast->next->next)
fast = fast->next->next;
else
fast = fast->next;
pre = low;
low = low->next;
}
pre->next = low ->next;
return head;
}
};
118
11/24
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
res.push_back({1});
if(numRows==1)return res;
res.push_back({1,1});
for(int i = 2 ; i < numRows ; ++i){
vector<int> tmp(i+1,1);
for(int j = 1 ; j < i ; ++j){
tmp[j] = res[i-1][j]+res[i-1][j-1];
}
res.push_back(tmp);
}
return res;
}
};
108
11/24
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return dfs(nums,0,nums.size()-1);
}
TreeNode* dfs(vector<int>&nums,int left,int right){
if(left > right) return nullptr;
int mid = left + (right - left)/2 ;
TreeNode* node = new TreeNode(nums[mid]);
node->left = dfs(nums,left,mid-1);
node->right = dfs(nums,mid+1,right);
return node;
}
};
剑指offer II 24
11/23
反转链表,就非要用别的方式
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head)return nullptr;
ListNode* p = head;
stack<ListNode*> st;
while(p){
st.push(p);
p = p->next;
}
head = st.top();
ListNode* q = st.top();
st.pop();
while(!st.empty()){
q->next = st.top();
st.pop();
q = q->next;
}
q->next = nullptr;
return head;
// ListNode* prev = nullptr;
// ListNode* curr = head;
// while (curr) {
// ListNode* next = curr->next;
// curr->next = prev;
// prev = curr;
// curr = next;
// }
// return prev;
}
};
剑指offer II 41
2021/11/23
200道题了
class MovingAverage {
public:
/** Initialize your data structure here. */
int size;
queue<int> q;
int res;
MovingAverage(int val) {
size = val;
res = 0;
}
double next(int val) {
q.push(val);
res += val;
if(q.size() > size){
res -= q.front();
q.pop();
return (double)res/size;
}
return (double)res/q.size();
}
};
剑指offer 59
2021/11/21
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
deque<int> q;
for(int right = 0 ; right < nums.size() ; ++ right){
while(!q.empty() && nums[right] > nums[q.back()])
q.pop_back();
q.push_back(right);
int left = right - k + 1;
if(left > q.front())
q.pop_front();
if(right + 1 >= k)
res.push_back(nums[q.front()]);
}
return res;
}
};
剑指offer 51
2021/11/20
class Solution {
public:
int reversePairs(vector<int>& nums) {
vector<int> tmp(nums.size());
return merge_sort(0,nums.size()-1,nums,tmp);
}
int merge_sort(int left,int right,vector<int>& nums,vector<int>& tmp){
if(left >= right)return 0;
int mid = ( left + right ) / 2;
int res = merge_sort(left,mid,nums,tmp) + merge_sort(mid+1,right,nums,tmp);
//tmp.assign(nums.begin(),nums.end()); 超出时间限制
for (int k = left; k <= right; k++)
tmp[k] = nums[k];
int i = left,j = mid + 1;
for(int k = left ; k <= right ; ++k){
if(i == mid + 1)nums[k] = tmp[j++];
// else if(j == right + 1)nums[k] = tmp[i++];
// else if(tmp[i] <= tmp[j])nums[k] = tmp[i++];
else if(j == right + 1 || tmp[i] <= tmp[j])nums[k] = tmp[i++];
else{
nums[k] = tmp[j++];
res += mid - i + 1;
}
}
return res;
}
};
剑指offer 41
class MedianFinder {
public:
priority_queue<int> small;
priority_queue<int, vector<int>, greater<int> > big;
int num_size;
/** initialize your data structure here. */
MedianFinder() {
num_size = 0;
}
void addNum(int num) {
small.push(num);
big.push(small.top());
small.pop();
small.push(big.top());
big.pop();
++num_size;
if(small.size() - big.size() == 2){big.push(small.top());small.pop();}
}
double findMedian() {
if(num_size%2){
return small.top();
}else{
return (double)(small.top() + big.top())/2;
}
}
};
剑指offer 20
又是看答案的一天,这题eeee
class Solution {
public:
bool isNumber(string s) {
vector<vector<pair<char,int>>> state = {
{make_pair(' ',0),make_pair('s',1),make_pair('d',2),make_pair('.',4)},
{make_pair('d',2),make_pair('.',4)},
{make_pair('d',2),make_pair('.',3),make_pair('e',5),make_pair(' ',8)},
{make_pair('d', 3), make_pair('e', 5), make_pair(' ', 8)},
{make_pair('d', 3)},
{make_pair('s', 6), make_pair('d', 7) },
{make_pair('d', 7) },
{make_pair('d', 7) , make_pair(' ', 8)},
{make_pair(' ', 8)}
};
int p = 0 ;
char t;
for(auto& c : s){
if('0' <= c && c <= '9')t = 'd';
else if(c == '+' || c == '-') t = 's';
else if(c == 'e' || c == 'E') t = 'e';
else if(c == '.' || c == ' ') t = c;
else t = '?';
int flag = 0;
for(auto& st :state[p]){
if(st.first == t){
flag = 1;
p = st.second;
}
}
if(!flag) return false;
}
return p == 2 || p == 3 || p == 7 || p == 8;
}
};
剑指offer 44
11/15
自己有点傻逼了
class Solution {
public:
int findNthDigit(int n) {
int digit = 1;
long start = 1;
long count = 9;
while (n > count) {
n -= count;
digit += 1;
start *= 10;
count = digit * start * 9;
}
long num = start + (n - 1) / digit;
return to_string(num)[(n - 1) % digit]-'0';
}
};
剑指offer 26
11/11
class Solution {
public:
bool isSubStructure(TreeNode* A, TreeNode* B) {
if(!A||!B)return false;
return check(A,B) || isSubStructure(A->left,B) || isSubStructure(A->right,B);
}
bool check(TreeNode* A, TreeNode* B){
if(!B)return true;
if(!A || A->val != B->val)return false;
return check(A->right,B->right)&&check(A->left,B->left);
}
};
剑指offer 46
11/10
不知不觉就快双十一了
class Solution {
public:
int translateNum(int num) {
string s = to_string(num);
int n = s.size();
int p_i_2 = 0,p_i_1 = 0,p_i = 1;
for(int i = 1; i <= n; i++){
p_i_2 = p_i_1;
p_i_1 = p_i;
// p_i = p_i_1;
if(i > 1){
int t = (s[i - 2] - '0') * 10 + s[i - 1] - '0';
if(t >= 10 && t <= 25)
p_i += p_i_2;
}
}
return p_i;
}
};
// class Solution {
// public:
// int translateNum(int num) {
// string s = to_string(num);
// int n = s.size();
// vector<int> f(n + 1);
// f[0] = 1;
// for(int i = 1; i <= n; i++){
// f[i] = f[i - 1];
// if(i > 1){
// int t = (s[i - 2] - '0') * 10 + s[i - 1] - '0';
// if(t >= 10 && t <= 25)
// f[i] += f[i - 2];
// }
// }
// return f[n];
// }
// };
剑指offer 59
11/9
class MaxQueue {
public:
queue<int> _queue;
deque<int> _deque;
MaxQueue() {
}
int max_value() {
if(!_deque.empty())
return _deque.front();
return -1;
}
void push_back(int value) {
_queue.push(value);
while(!_deque.empty()&&(_deque.back()< value))_deque.pop_back();
_deque.push_back(value);
}
int pop_front() {
if(_queue.empty())return -1;
if(_queue.front() == _deque.front())_deque.pop_front();
int res = _queue.front();
_queue.pop();
return res;
}
};
剑指offer 60
11/8
class Solution {
public:
vector<double> dicesProbability(int n) {
vector<double> pre(6);
for(int i=0;i<6;++i) pre[i]=1.0/6;
for(int i = 2 ; i <= n ; ++i){
vector<double> tmp(5*i+1,0);
for(int k = 0 ; k < pre.size() ;k++){
for(int j = 0 ; j < 6 ;j++){
tmp[k+j] += pre[k]/6;
}
}
pre = tmp;
}
return pre;
}
};
剑指offer 34
11/7
class Solution {
public:
vector<vector<int>> res;
vector<int> res_tmp;
int target_tmp = 0;
vector<vector<int>> pathSum(TreeNode* root, int target) {
dfs(root,target);
return res;
}
void dfs(TreeNode* root,int target){
if(!root)return;
target_tmp += root->val;
res_tmp.push_back(root->val);
if((target == target_tmp) && !(root->left) && !(root->right))res.push_back(res_tmp);
dfs(root->left,target);
dfs(root->right,target);
target_tmp -= root->val;
res_tmp.pop_back();
}
};
剑指offer 32 |||
11/5
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if(!root)return {};
vector<vector<int>> res;
deque<TreeNode*> dq;
int layer = 1;
dq.push_back(root);
while(!dq.empty()){
vector<int> tmp;
int len = dq.size();
while(len--){
if(layer & 1){
tmp.push_back(dq.front()->val);
if(dq.front()->left)dq.push_back(dq.front()->left);
if(dq.front()->right)dq.push_back(dq.front()->right);
dq.pop_front();
}else{
tmp.push_back(dq.back()->val);
if(dq.back()->right)dq.push_front(dq.back()->right);
if(dq.back()->left)dq.push_front(dq.back()->left);
dq.pop_back();
}
}
res.push_back(tmp);
++layer;
}
return res;
}
};
剑指offer 32
11/4
class Solution {
public:
vector<int> levelOrder(TreeNode* root) {
if(!root)return {};
queue<TreeNode*> q;
vector<int> res;
q.push(root);
while(!q.empty()){
if(q.front()->left)q.push(q.front()->left);
if(q.front()->right)q.push(q.front()->right);
res.push_back(q.front()->val);
q.pop();
}
return res;
}
};
剑指offer 49
11/4
class Solution {
public:
int nthUglyNumber(int n) {
int a = 0,b = 0,c = 0;
vector<int> dp(n);
dp[0] = 1;
for(int i = 1 ; i < n ; ++i){
int tmp2 = dp[a]*2,tmp3 = dp[b]*3,tmp5 = dp[c]*5;
dp[i] = min(tmp2,min(tmp3,tmp5));
if(dp[i] == tmp2)++a;
if(dp[i] == tmp3)++b;
if(dp[i] == tmp5)++c;
}
return dp[n-1];
}
};
剑指offer 47
11/3
class Solution {
public:
// 动态规划
int maxValue(vector<vector<int>>& grid) {
vector<vector<int>> dp(grid.size(),vector<int>(grid[0].size(),0));
for(int i = 0 ; i < grid.size() ; ++i){
for(int j = 0 ; j < grid[0].size() ; ++j){
if(i == 0 && j == 0)dp[i][j] = grid[i][j];
else if(i == 0 && j != 0)dp[i][j] = dp[i][j-1] + grid[i][j];
else if(i != 0 && j == 0)dp[i][j] = dp[i-1][j] + grid[i][j];
else dp[i][j] = max(dp[i-1][j] , dp[i][j-1]) + grid[i][j];
}
}
return dp[grid.size()-1][grid[0].size()-1];
}
};
剑指offer 56
11/2
class Solution {
public:
vector<int> singleNumbers(vector<int>& nums) {
int tmp = 0, m = 1,x = 0, y = 0;
for(auto& c : nums)tmp ^= c;
while((tmp & m) == 0) m <<= 1;
for(auto& c : nums){
if((c & m))x ^= c;
else y ^= c;
}
return {x,y};
}
};
剑指offer 35
11/1
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head) return nullptr;
Node* cur = head;
unordered_map<Node*, Node*> map;
while(cur){
map[cur] = new Node(cur->val);
cur = cur->next;
}
cur = head;
while(cur){
map[cur]->next = map[cur->next];
map[cur]->random = map[cur->random];
cur = cur->next;
}
return map[head];
}
};
剑指offer 58
10/30
class Solution {
public:
string reverseWords(string s) {
if(!s.size())return "";
int i = 0,j = 0 , n = s.size()-1;
stack<string> word;
string res = "";
if(!n && s != " ")return s;
if(!n)return "";
while(i < n){
while(i < n && s[i] == ' ')++i;
j = i;
while(j <= n && s[j] != ' ')++j;
if(s.substr(i,j-i) != "")word.push(s.substr(i,j-i));
i = j;
}
while(!word.empty()){
res += word.top();
if(word.size() != 1)res += ' ';
word.pop();
}
return res;
}
};
剑指offer 57
10/25
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i = 0 , j = nums.size()-1,sum = 0;
while(true){
sum = nums[i]+nums[j];
if(sum == target)break;
if(sum < target)++i;
if(sum > target)--j;
}
return {nums[i],nums[j]};
}
};
剑指offer 32
10/25
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
vector<vector<int>> res;
if(!root)return res;
q.push(root);
while(!q.empty()){
vector<int> tmp;
int s = q.size();
for(int i = 0 ; i < s ; ++i){
tmp.push_back(q.front()->val);
if(q.front()->left)q.push(q.front()->left);
if(q.front()->right)q.push(q.front()->right);
q.pop();
}
res.push_back(tmp);
}
return res;
}
};
剑指offer 39
10/24/
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int,int> hash;
int res_num = 0, max_num = 0 ;
for(auto& i : nums){
++hash[i];
if(hash[i] > max_num){
res_num = i;
max_num = hash[i];
}
}
return res_num;
}
};
剑指offer
10/24
class Solution {
public:
vector<vector<int>> findContinuousSequence(int target) {
vector<vector<int>> res;
int left = 1, right = 2, sum = 3;
while(left < right){
if(sum == target){
vector<int> r;
for(int i = left ; i <= right ; ++i) r.push_back(i);
res.push_back(r);
}
if(sum < target){
++right;
sum += right;
}else if (sum >= target){
sum -= left;
++left;
}
}
return res;
}
};
剑指offer 68
10/23
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(p->val < root->val && q->val < root->val)
return lowestCommonAncestor(root->left,p,q);
if(p->val > root->val && q->val > root->val)
return lowestCommonAncestor(root->right,p,q);
return root;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || root == p || root == q) return root;
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);
if(left == nullptr && right == nullptr) return nullptr;
if(left == nullptr) return right;
if(right == nullptr) return left;
return root;
}
};
剑指offer 17
21/10/23
class Solution {
public:
vector<int> res;
vector<int> printNumbers(int n) {
string path(n,'0');
dfs(n,0,path);
return res;
}
void dfs(int n,int x,string str){
if(x == n){
int val = std::stoi(str);
if(val)res.push_back(val);
return;
}
for(int i = 0 ; i < 10 ; ++i ){
str[x] = i + '0';
dfs(n,x+1,str);
}
}
};
剑指offer 29
21/10/22
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(!matrix.size()) return {};
vector<int> res;
int left = 0,right = matrix[0].size()-1,top = 0,bottom = matrix.size()-1;
while(true){
for(int i = left ; i <= right;++i)res.push_back(matrix[top][i]);
if(++top > bottom)break;
for(int i = top ; i <= bottom;++i)res.push_back(matrix[i][right]);
if(--right < left)break;
for(int i = right ; i >= left;--i)res.push_back(matrix[bottom][i]);
if(--bottom < top)break;
for(int i = bottom ; i >= top;--i)res.push_back(matrix[i][left]);
if(++left > right)break;
}
return res;
}
};
剑指offer54
10/22
class Solution {
public:
int count = 0,res = 0;
int kthLargest(TreeNode* root, int k) {
dfs(root,k);
return res;
}
void dfs(TreeNode* node,int k){
if(!node)return;
dfs(node->right,k);
++count;
if(count == k) res = node->val;
dfs(node->left,k);
}
};
剑指offer21
2021/10/21
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int i = 0 , j = nums.size()-1,p=0;
while(i < j){
while(i<j && nums[i]%2 == 1)++i;
while(i<j && nums[j]%2 == 0)--j;
swap(nums[i++],nums[j--]);
}
return nums;
}
};
剑指offer27
2021/10/21
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(!root)return nullptr;
TreeNode* tmp = root->right;
root->right = mirrorTree(root->left);
root->left = mirrorTree(tmp);
return root;
}
};
10. 正则表达式匹配
2021/10/20
热题 hot 100结束了
class Solution {
public:
//犯了一个错误,最后才想明白,就是被注释的代码,竟然想到用for循环找单个字符
bool isMatch(string s, string p) {
vector<vector<bool>> dp(s.size()+1,vector<bool>(p.size()+1,false));
dp[0][0] = true;
for(int i = 1 ; i < dp[0].size() ; ++i){
// for(auto &c : p){
char c = p[i-1];
if(c == '*' && i > 1)
dp[0][i] = dp[0][i-2];
if(i == 1 && c == '*')
dp[0][i] = true;
// }
}
for(int i = 1 ; i < dp.size() ; ++i){
//for(auto &c : s){
char c = s[i-1];
for(int j = 1 ; j < dp[i].size() ; ++j){
char m = p[j-1];
if(c == m || m == '.'){
dp[i][j] = dp[i-1][j-1];
}else if(m == '*'){
if(j > 1){
if(dp[i][j-2] == true)
dp[i][j] = true;
else{
char m_prv = p[j-2];
if(m_prv == c || m_prv == '.')
dp[i][j] = dp[i-1][j];
}
}
}
}
//}
}
return dp[s.size()][p.size()];
}
};
32. 最长有效括号
2021/10/19
class Solution {
public:
int longestValidParentheses(string s) {
int longest_len = 0 ;
stack<int> l_stack;
l_stack.push(-1);
for(int i = 0 ; i < s.size() ; ++i){
if(s[i] == '('){
l_stack.push(i);
}else{
l_stack.pop();
if(l_stack.empty()){
l_stack.push(i);
}else{
longest_len = max(longest_len,i-l_stack.top());
}
}
}
return longest_len;
}
};
76. 最小覆盖子串
2021/10/18
class Solution {
public:
string minWindow(string s, string t) {
int cnt= 0 ,count = t.size();
unordered_map<char, int> tt,ss;
string res;
for(auto& c : t)++tt[c];
for(int i = 0 , j = 0 ; i < s.size() ; ++i){
++ss[s[i]];
if(ss[s[i]] <= tt[s[i]])++cnt;
while(ss[s[j]] > tt[s[j]])--ss[s[j++]];
if(cnt == count){
if(res.empty() || i-j+1 < res.size()){
res = s.substr(j,i-j+1);
}
}
}
return res;
}
};
239. 滑动窗口最大值
2021/10/18
用对队列
class MyQueue {
private:
deque<int> data;
public:
void push(int n) {
while (!data.empty() && data.back() < n)
data.pop_back();
data.push_back(n);
}
int max() { return data.front(); }
void pop(int n) {
if (!data.empty() && data.front() == n)
data.pop_front();
}
};
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MyQueue window;
vector<int> res;
for(int i = 0 ; i < k-1 ; ++i) window.push(nums[i]);
for (int i = k-1; i < nums.size(); i++) {
window.push(nums[i]);
res.push_back(window.max());
window.pop(nums[i - k + 1]);
}
return res;
}
};
85. 最大矩形
2021/10/17
用84题解决
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int res = 0 ,len = heights.size();
stack<int> my_stack;
vector<int> new_heights(len+2,0);
for(int i = 1 ; i < len + 1 ; ++i)new_heights[i] = heights[i-1];
for(int i = 0 ; i < len+2 ; ++i){
while(!my_stack.empty() && new_heights[i] < new_heights[my_stack.top()]){
int cur = my_stack.top();
my_stack.pop();
int cur_height = new_heights[cur];
int left = my_stack.top();
int right = i;
int width = right - left - 1;
res = max(res,cur_height*width);
}
my_stack.push(i);
}
return res;
}
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.size() == 0)return 0;
int row = matrix.size(),col = matrix[0].size();
vector<int> tmp(col,0);
//for(int i = 0 ; i < col ; ++i)tmp[i] = atoi(matrix[0][i]);
//此处char 转int 不知道为什么这个函数说没有,换了写法
int res = largestRectangleArea(tmp);
for(int i = 0 ; i < row ; ++i){
for(int j = 0 ; j < col ; ++j){
//tmp[j] += atoi(matrix[i][j]);
if(matrix[i][j] == '1'){
++tmp[j];
}else{
tmp[j] = 0;
}
}
res = max(res,largestRectangleArea(tmp));
}
return res;
}
};
84. 柱状图中最大的矩形
2021/10/16
单调栈
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int res = 0 ,len = heights.size();
stack<int> my_stack;
vector<int> new_heights(len+2,0);
for(int i = 1 ; i < len + 1 ; ++i)new_heights[i] = heights[i-1];
for(int i = 0 ; i < len+2 ; ++i){
while(!my_stack.empty() && new_heights[i] < new_heights[my_stack.top()]){
int cur = my_stack.top();
my_stack.pop();
int cur_height = new_heights[cur];
int left = my_stack.top();
int right = i;
int width = right - left - 1;
res = max(res,cur_height*width);
}
my_stack.push(i);
}
return res;
}
};
301. 删除无效的括号
2021/10/15
有点难
class Solution {
public:
bool Is_Valid(const string& s){
int count = 0;
for( char c : s){
if(c == '(')++count;
if(c == ')')--count;
if(count < 0)return false;
}
return count == 0 ;
}
vector<string> removeInvalidParentheses(string s) {
unordered_set<string> word{s};
while(true){
unordered_set<string> res;
for(auto& w : word){
if(Is_Valid(w))
res.insert(w);
}
if(!res.empty())
return vector<string>(res.begin(),res.end());
unordered_set<string> next_word;
for (const string& t : word) {
for (int i = 0; i < t.length(); ++i) {
if (t[i] == '(' || t[i] == ')') {
next_word.insert(t.substr(0, i) + t.substr(i+1,t.size()-i-1));
}
}
}
word = next_word;
}
return {};
}
};
312. 戳气球
2021/10/14
class Solution {
public:
int maxCoins(vector<int>& nums) {
int len = nums.size();
if(!len)return 0;
vector<int> arr(len+2,1);
vector<vector<int>> dp(len+2,vector<int>(len+2));
for(int i = 1 ; i <= len ; ++i)arr[i] = nums[i-1];
for(int i = len - 1 ; i >= 0 ; i--){
for (int j = i + 2 ; j <= len + 1 ; j++){
for(int k = i + 1 ; k < j ; k++){
int sum = arr[i] * arr[k] * arr[j];
sum += dp[i][k] + dp[k][j];
dp[i][j] = max(dp[i][j],sum);
}
}
}
return dp[0][len+1];
}
};
72. 编辑距离
2021/10/13
动态规划
class Solution {
public:
int minDistance(string word1, string word2) {
int row = word1.size(),col = word2.size();
vector<vector<int>> dp(row+1,vector<int>(col+1));
for(int i = 0 ; i <= row ; ++i)dp[i][0] = i;
for(int i = 0 ; i <= col ; ++i)dp[0][i] = i;
for(int i = 1 ; i <= row ; ++i){
for(int j = 1 ; j <= col ; ++j){
if(word1[i-1] == word2[j-1]){
dp[i][j] = dp[i-1][j-1];
}else{
dp[i][j] = min(dp[i-1][j],min(dp[i-1][j-1],dp[i][j-1]))+1;
}
}
}
return dp[row][col];
}
};
297. 二叉树的序列化与反序列化
2021/10/12
中等级别
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(!root)return "None";
return to_string(root->val)+","+ serialize(root->left)+","+serialize(root->right);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
list<string> array;
string tmp;
for(auto& ch :data){
if(ch != ','){
tmp.push_back(ch);
}else{
array.push_back(tmp);
tmp.clear();
}
}
array.push_back(tmp);
return dfs(array);
}
TreeNode* dfs(list<string>& array){
if(array.front() == "None"){
array.erase(array.begin());
return nullptr;
}
TreeNode* root = new TreeNode(stoi(array.front()));
array.erase(array.begin());
root->left = dfs(array);
root->right = dfs(array);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));
42. 接雨水
2021/10/11
//author : Aen
//blog : https://aeneag.xyz
//公众号 : 技术乱舞
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
if (!n) return 0;
vector<int> leftMax(n),rightMax(n);
leftMax[0] = height[0];
rightMax[n - 1] = height[n - 1];
for (int i = 1,j = n-2; i < n, j >= 0; ++i,--j) {
leftMax[i] = max(leftMax[i - 1], height[i]);
rightMax[j] = max(rightMax[j + 1], height[j]);
}
int ans = 0;
for (int i = 0; i < n; ++i)ans += min(leftMax[i], rightMax[i]) - height[i];
return ans;
}
};
152. 乘积最大子数组
2021/10/10
动态规划 思想
class Solution {
public:
int maxProduct(vector<int>& nums) {
int len = nums.size(),res = nums[0];
vector<int> f(len+1,0),g(len+1,0);
f[0] = nums[0],g[0] = nums[0];
for(int i = 1 ; i < len ; ++i){
f[i] = max(nums[i], max(f[i - 1] * nums[i], g[i - 1] * nums[i]));
g[i] = min(nums[i], min(g[i - 1] * nums[i], f[i - 1] * nums[i]));
res = max(res,f[i]);
}
return res;
}
};
class Solution {
public:
int maxProduct(vector<int>& nums) {
int len = nums.size(),res = nums[0];
int max_num= nums[0] , min_num = nums[0],max_tmp = nums[0],min_tmp = nums[0];
for(int i = 1 ; i < len ; ++i){
max_tmp = max_num,min_tmp = min_num;
max_num = max(nums[i], max(max_tmp * nums[i], min_tmp * nums[i]));
min_num = min(nums[i], min(max_tmp * nums[i], min_tmp * nums[i]));
res = max(res,max_num);
}
return res;
}
};
/*
* [2 3 -2 4]
* 动态规划
* f[i] g[i] 表示以当前节点结尾的连续子数组的max,min值
* 首先我们不知道最大值是否是正数还是负数
* 1) 计算最大值
* 当nums[i] >= 0 时
* 1.把当前节点的值看作子数组,
* 2.当前节点与前一个最大连续子数组(f[i-1])相乘,组成该节点的子数组
* 当nums[i] < 0 时
* 1.把当前节点的值看作子数组,
* 2.当前节点与前一个最小连续子数组(g[i-1])相乘,组成该节点的子数组
* 最后比较最大值
* nums[i] nums[i]*f[i-1] nums[i]*g[i-1]
* 2) 计算最小值
* 当nums[i] >= 0 时
* 1.把当前节点的值看作子数组,
* 2.当前节点与前一个最小连续子数组(g[i-1])相乘,组成该节点的子数组
* 当nums[i] < 0 时
* 1.把当前节点的值看作子数组,
* 2.当前节点与前一个最小连续子数组(f[i-1])相乘,组成该节点的子数组
* 最后比较最大值
* nums[i] nums[i]*f[i-1] nums[i]*g[i-1]
*/
221. 最大正方形
2021/10/10
什么时候可以自己想到方法
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int row = matrix.size(),col = matrix[0].size(),res = 0;
if(!row || !col)return 0;
vector<vector<int>> dp(row,vector<int>(col,0));
for(int i = 0 ; i < row ; ++i){
for(int j = 0 ; j < col ; ++j){
if(matrix[i][j] == '1'){
if(!i || !j){
dp[i][j] = 1;
}else{
dp[i][j] = min(dp[i][j-1],min(dp[i-1][j],dp[i-1][j-1]))+1;
}
res = max(res,dp[i][j]);
}
}
}
return res*res;
}
};
238. 除自身以外数组的乘积
2021/10/9
第二题
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int len = nums.size();
vector<int> res(len,0);
int left = 1 , right = 1;
for(int i = 0 ; i < len ; ++i){
res[i] = left;
left *= nums[i];
}
for(int i = len - 1 ; i > 0 ; --i){
right *= nums[i];
res[i-1] *= right;
}
return res;
}
};
240. 搜索二维矩阵 II
2021/10/9
刷题记录会在csdn同步更新
算法真的妙
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int col = matrix[0].size(),row = matrix.size();
int i = 0 ,j = col - 1 ;
if(!row&&!col)return false;
while(i < row && j >= 0){
if(matrix[i][j] == target)return true;
else if(matrix[i][j] < target)++i;
else if(matrix[i][j] > target)--j;
}
return false;
}
};
300. 最长递增子序列
2021/10/8
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int len = nums.size();
if(!len)return 0;
vector<int> dp(len,1);
for(int i = 0 ; i <len ; ++i){
for(int j = 0 ; j < i ; ++j){
if(nums[j]<nums[i])dp[i] = max(dp[i],dp[j]+1);
}
}
return *max_element(dp.begin(),dp.end());
}
};
139. Word Break 单词拆分
2021/10/7
今天又做了一个决策,算法输出到csdn,要更专业
动态规划
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int len = s.size();
auto wordDictSet = unordered_set <string>();//新建一个无序集合
for(auto word : wordDict)wordDictSet.insert(word);//子单词插入到这个无序集合中
auto dp = vector<bool> (len+1);//动态规划dp数组
dp[0] = true;//第一项说明空串是true
for(int i = 1 ; i <= len ; ++i){ // for循序,dp[i]如果是true意思是说前i个串匹配到
for(int j = 0 ; j < i ; ++j){
if(dp[j] && wordDictSet.find(s.substr(j,i-j)) != wordDictSet.end()){
dp[i] = true;
break;//如果匹配到就跳出这个循环,继续下一个i
}
}
}
return dp[len];
}
};
322. 零钱兑换
2021/10/6
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int len = coins.size();
vector<int> dp(amount+1,amount+1);
dp[0] = 0;
for(int i = 1 ; i <= amount ; ++i){
for(int j = 0 ; j < len ; ++j){
if(coins[j] <= i){
dp[i] = min(dp[i],dp[i - coins[j]]+1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
};
309. 最佳买卖股票时机含冷冻期
2021/10/5
动态规划 什么时候自己可以完全想到
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.empty())return 0;
int len = prices.size();
vector<vector<int>> dp(len,vector<int>(3));
dp[0][0] = -prices[0];
for(int i = 1 ; i < len ; ++i){
dp[i][0] = max(dp[i-1][0],dp[i-1][2] - prices[i]);
dp[i][1] = dp[i-1][0] + prices[i];
dp[i][2] = max(dp[i-1][2],dp[i-1][1]);
}
return max(dp[len-1][1],dp[len-1][2]);
}
};
399. 除法求值
2021/10/5
这个有点难,不是自己写的,别人怎么能想到 = =,理解代码
class Solution {
public:
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
int nvars = 0;
unordered_map<string, int> variables;
int n = equations.size();
for (int i = 0; i < n; i++) {
if (variables.find(equations[i][0]) == variables.end()) {
variables[equations[i][0]] = nvars++;
}
if (variables.find(equations[i][1]) == variables.end()) {
variables[equations[i][1]] = nvars++;
}
}
vector<vector<double>> graph(nvars, vector<double>(nvars, -1.0));
for (int i = 0; i < n; i++) {
int va = variables[equations[i][0]], vb = variables[equations[i][1]];
graph[va][vb] = values[i];
graph[vb][va] = 1.0 / values[i];
}
for (int k = 0; k < nvars; k++) {
for (int i = 0; i < nvars; i++) {
for (int j = 0; j < nvars; j++) {
if (graph[i][k] > 0 && graph[k][j] > 0) {
graph[i][j] = graph[i][k] * graph[k][j];
}
}
}
}
vector<double> ret;
for (const auto& q: queries) {
double result = -1.0;
if (variables.find(q[0]) != variables.end() && variables.find(q[1]) != variables.end()) {
int ia = variables[q[0]], ib = variables[q[1]];
if (graph[ia][ib] > 0) {
result = graph[ia][ib];
}
}
ret.push_back(result);
}
return ret;
}
};
207. 课程表
2021/10/3
菜狗就是自己
class Solution {
public:
vector<vector<int>> edges;
vector<int> visited;
bool res = true;
void dfs(int u){
visited[u] = 1;
for(auto v: edges[u]){
if(!visited[v]){
dfs(v);
if(!res)return;
}else if(visited[v] == 1){
res = false;
return;
}
}
visited[u] = 2;
}
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
edges.resize(numCourses);
visited.resize(numCourses);
for(auto& info:prerequisites){
edges[info[1]].push_back(info[0]);
}
for(int i = 0 ; i < numCourses && res; ++i){
if(!visited[i])dfs(i);
}
return res;
}
};
128. 最长连续序列
2021/10/2
自己总是想不到,c用习惯了想不到用库
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> hash;
for(auto x : nums)hash.insert(x);
int res = 0,y = 0;
for(auto x :nums){
if(!hash.count(x-1)){
y = x;
while(hash.count(y+1))y++;
res = max(res,y-x+1);
}
}
return res;
}
};
200. 岛屿数量
2021/10/1
为什么自己想不到这个
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int res = 0;
int row = grid.size(),col = grid[0].size();
for(int i = 0 ; i < row ; ++i){
for(int j = 0 ; j < col ; ++j){
if(grid[i][j] == '1'){
dfs(grid,i,j,row,col);
++res;
}
}
}
return res;
}
void dfs(vector<vector<char>>& grid,int i , int j,int row,int col){
if(i<0 || i >= row|| j<0 || j >= col || grid[i][j] == '0')return;
grid[i][j] = '0';
dfs(grid,i+1,j,row,col);
dfs(grid,i-1,j,row,col);
dfs(grid,i,j+1,row,col);
dfs(grid,i,j-1,row,col);
}
};
则移山填海之难,
终有成功之日!
——孙文
- introduction
- algorithm
- 剑指offer II 23
- 328. 奇偶链表
- 445. 两数相加
- 725. 分隔链表
- 86. 分隔链表
- 61. 旋转链表
- 817. 链表组件
- 剑指offer || 28
- 剑指offer || 78
- 剑指offer || 27 回文链表
- 剑指offer || 26
- 剑指offer II 77
- 1669 合并两个链表
- 剑指offer II 21 删除倒数第k个节点
- 2095 删除链表中的中间节点
- 118
- 108
- 剑指offer II 24
- 剑指offer II 41
- 剑指offer 59
- 剑指offer 51
- 剑指offer 41
- 剑指offer 20
- 剑指offer 44
- 剑指offer 26
- 剑指offer 46
- 剑指offer 59
- 剑指offer 60
- 剑指offer 34
- 剑指offer 32 |||
- 剑指offer 32
- 剑指offer 49
- 剑指offer 47
- 剑指offer 56
- 剑指offer 35
- 剑指offer 58
- 剑指offer 57
- 剑指offer 32
- 剑指offer 39
- 剑指offer
- 剑指offer 68
- 剑指offer 17
- 剑指offer 29
- 剑指offer54
- 剑指offer21
- 剑指offer27
- 10. 正则表达式匹配
- 32. 最长有效括号
- 76. 最小覆盖子串
- 239. 滑动窗口最大值
- 85. 最大矩形
- 84. 柱状图中最大的矩形
- 301. 删除无效的括号
- 312. 戳气球
- 72. 编辑距离
- 297. 二叉树的序列化与反序列化
- 42. 接雨水
- 152. 乘积最大子数组
- 221. 最大正方形
- 238. 除自身以外数组的乘积
- 240. 搜索二维矩阵 II
- 300. 最长递增子序列
- 139. Word Break 单词拆分
- 322. 零钱兑换
- 309. 最佳买卖股票时机含冷冻期
- 399. 除法求值
- 207. 课程表
- 128. 最长连续序列
- 200. 岛屿数量
不知不觉,也刷了不少题了
测试
test