121买卖股票的最佳时机【简单】
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
- 简单dp
class Solution {
public:
int maxProfit(vector<int>& prices) {
vector<int> dp(prices.size()+1, 10001);
//dp[i]=i前最小的
int res=0;
for(int i=1; i<prices.size(); i++)
{
dp[i]=min(prices[i-1],dp[i-1]);
res=max(prices[i]-dp[i],res);
}
return res;
}
};
141环形链表【简单】
https://leetcode-cn.com/problems/linked-list-cycle/
- 快慢指针
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* fast=head;
ListNode* slow=head;
while(fast!=NULL&&fast->next!=NULL)
{
fast = fast->next->next;
slow = slow->next;
if(fast==slow)
return true;
}
return false;
}
};
160相交链表【简单】
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
- 双指针,如果if条件是
ptr1==NULL
可以不需要特判/统计重复访问
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* ptr1 = headA;
ListNode* ptr2 = headB;
while(ptr1!=ptr2)
{
if(ptr1==NULL)
ptr1 = headB;
else ptr1 = ptr1->next;
if(ptr2==NULL)
ptr2 = headA;
else ptr2 = ptr2->next;
}
return ptr2;
}
};
剑指 Offer 26. 树的子结构【中等】
https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof/
class Solution {
public:
bool isSame(TreeNode* a, TreeNode* b)
{
if(b==NULL)
return true;
if(a==NULL)
return false;
if(a->val!=b->val)
return false;
return isSame(a->left, b->left)&&isSame(a->right, b->right);
}
bool isSubStructure(TreeNode* A, TreeNode* B) {
if(A==NULL||B==NULL)
return false;
return isSame(A, B)||isSubStructure(A->left, B)||isSubStructure(A->right, B);
}
};
102二叉树的层序遍历【中等】
https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
- 使用queue
- 处理完同一层的每个节点cnt++,每次处理cnt个即可把每一层分开
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
vector<vector<int>> res;
if(root==nullptr)
return res;
int cnt=1;
while(!q.empty())
{
int cur = cnt;
cnt=0;
vector<int> ans;
for(int i=0; i<cur; i++)
{
TreeNode* tmp = q.front();
ans.push_back(tmp->val);
q.pop();
if(tmp->left!=nullptr)
{
q.push(tmp->left);
cnt++;
}
if(tmp->right!=nullptr)
{
q.push(tmp->right);
cnt++;
}
}
res.push_back(ans);
}
return res;
}
};