1. #include<iostream>
  2. #include<sstream>
  3. #include<vector>
  4.  
  5. std::vector<int> split(std::string& str, char delim = ' ') {
  6. std::stringstream ss(str);
  7. std::string tempStr;
  8. std::vector<int> vector;
  9.  
  10. while (getline(ss, tempStr, delim)) {
  11. vector.push_back(atoi(tempStr.c_str()));
  12. }
  13.  
  14. return vector;
  15. }
  16.  
  17. int main() {
  18. std::string ret;
  19. int ans = 0;
  20. while (getline(std::cin, ret, '\n')) {
  21. std::vector<int> vector = split(ret);
  22. ans = vector[0] + vector[1];
  23. std::cout << ans << std::endl;
  24. }
  25.  
  26. return 0;
  27. }

3. 无重复字符的最长子串

  1. #include <iostream>
  2. #include <unordered_set>
  3.  
  4. class Solution {
  5. public:
  6. int lengthOfLongestSubstring(std::string s) {
  7. int length = s.size();
  8. int maxLength = 0;
  9. int lastMaxLength = 0;
  10. std::unordered_set<char> unorderedSet;
  11. //std::set<int> set;
  12.  
  13. for (int i = 0; i < length; ++i) {
  14. unorderedSet.clear();
  15. for (int j = i; j < length; ++j) {
  16. if (unorderedSet.find(s[j]) != unorderedSet.end()) {
  17. break;
  18. }
  19. unorderedSet.insert(s[j]);
  20. int nowLength = unorderedSet.size();
  21. maxLength = nowLength > lastMaxLength ? nowLength : lastMaxLength;
  22. }
  23. lastMaxLength = maxLength;
  24. }
  25. return maxLength;
  26. }
  27. };

49. 字母异位词分组

  1. #include <iostream>
  2. #include <vector>
  3. #include <unordered_set>
  4. #include <map>
  5. #include <algorithm>
  6.  
  7. /* 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
  8.  
  9. 示例:
  10.  
  11. 输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
  12. 输出:
  13. [
  14. ["ate","eat","tea"],
  15. ["nat","tan"],
  16. ["bat"]
  17. ]
  18.  
  19. */
  20.  
  21. class Solution {
  22. public:
  23. std::vector<std::vector<std::string>> groupAnagrams(std::vector<std::string>& strs) {
  24. std::map<std::string, std::vector<std::string>> map;
  25. for (auto ss: strs) {
  26. std::string value = ss;
  27. std::sort(ss.begin(), ss.end());
  28. map[ss].push_back(value);
  29. }
  30.  
  31. std::vector<std::vector<std::string>> ret;
  32. for (auto it = map.begin(); it != map.end(); it++) {
  33. ret.push_back(it->second);
  34. }
  35.  
  36. return ret;
  37. }
  38. };

86. 分隔链表

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode() : val(0), next(nullptr) {}
  7. * ListNode(int x) : val(x), next(nullptr) {}
  8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. ListNode* partition(ListNode* head, int x) {
  14. ListNode* small = new ListNode(0);
  15. ListNode* smallHead = small;
  16. ListNode* large = new ListNode(0);
  17. ListNode* largeHead = large;
  18.  
  19. while (head != nullptr) {
  20. if (head->val < x) {
  21. small->next = head;
  22. small = small->next;
  23.  
  24. } else {
  25. large->next = head;
  26. large = large->next;
  27. }
  28.  
  29. head = head->next;
  30. }
  31.  
  32. large->next = nullptr;
  33. small->next = largeHead->next;
  34.  
  35. return smallHead->next;
  36.  
  37. }
  38. };

16. 最接近的三数之和

错误代码:这个思路会少算很多可能性!!!

  1. class Solution {
  2. public:
  3. int threeSumClosest(std::vector<int>& nums, int target) {
  4. if (nums.size() < 3) {
  5. return 0;
  6. }
  7.  
  8. std::sort(nums.begin(), nums.end());
  9.  
  10. int start = 0;
  11. int end = nums.size() - 1;
  12. int sum = 0;
  13. int ans = nums[0] + nums[1] + nums[2];
  14.  
  15. while (start < end) {
  16. //这里会少算很多可能性,这里只是计算了,s,s+1,e这种可能性,并没有算s+2,s+3,..的可能性,复杂度低了,但是结果就不对了,所以因此应该在外面再加一层循环,确保每一种可能性都被计算到
  17. sum = nums[start] + nums[start + 1] + nums[end];
  18.  
  19. if(std::abs(target - sum) < std::abs(target - ans))
  20. ans = sum;
  21.  
  22. if (sum < target) {
  23. start++;
  24. } else if (sum > target) {
  25. end--;
  26. } else {
  27. return ans;
  28. }
  29.  
  30. }
  31.  
  32. return ans;
  33. }

正确代码:

  1. class Solution {
  2. public:
  3. int threeSumClosest(std::vector<int>& nums, int target) {
  4. std::sort(nums.begin(), nums.end());
  5.  
  6. int s = 0;
  7. int e = nums.size() - 1;
  8. int ans = nums[0] + nums[1] + nums[2];
  9.  
  10. for (int i = 0; i < nums.size(); ++i) {
  11. s = i + 1;//在这里更新s,保证s可以中开始---一直跳到--->结尾
  12. e = nums.size() - 1;//e每次都要更新,因为可能在while循环中更新了e
  13. while (s < e) {
  14. int sum = nums[i] + nums[s] + nums[e];
  15. if (std::abs(target - ans) > std::abs(target - sum))
  16. ans = sum;
  17.  
  18. if (sum == target)
  19. return sum;
  20. if (sum < target)
  21. s++;
  22. if (sum > target)
  23. e--;
  24. }
  25. }
  26.  
  27. return ans;
  28. }
  29. };

27. 移除元素

  1. #include <vector>
  2.  
  3. class Solution {
  4. public:
  5. int removeElement(std::vector<int>& nums, int val) {
  6. int left = 0;
  7. //最终目标:保证(0, left)区间内一个val都没有
  8.  
  9. for (int right = 0; right < nums.size(); ++right) {
  10. if (nums[right] != val) {
  11. nums[left] = nums[right];
  12. left++;
  13. }
  14. }
  15.  
  16. return left;
  17. }
  18. };

641. 设计循环双端队列

  1. #include <vector>
  2.  
  3. class MyCircularDeque {
  4. private:
  5. std::vector<int> vector_;
  6. int length_{ 0 };
  7. public:
  8. /** Initialize your data structure here. Set the size of the deque to be k. */
  9. MyCircularDeque(int k) {
  10. length_ = k;
  11. //这里要用reserve不要用resize
  12. vector_.reserve(k);
  13. }
  14.  
  15. /** Adds an item at the front of Deque. Return true if the operation is successful. */
  16. bool insertFront(int value) {
  17. if (isFull())
  18. return false;
  19. vector_.insert(vector_.begin(), value);
  20. return true;
  21. }
  22.  
  23. /** Adds an item at the rear of Deque. Return true if the operation is successful. */
  24. bool insertLast(int value) {
  25. if (isFull())
  26. return false;
  27. vector_.push_back(value);
  28. return true;
  29. }
  30.  
  31. /** Deletes an item from the front of Deque. Return true if the operation is successful. */
  32. bool deleteFront() {
  33. if (isEmpty())
  34. return false;
  35. vector_.erase(vector_.begin());
  36. return true;
  37. }
  38.  
  39. /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
  40. bool deleteLast() {
  41. if (isEmpty())
  42. return false;
  43. //注意,删除最后一个元素的时候,要减1,迭代器(vector_.end())指向的是最后一个元素的下一个
  44. vector_.erase(vector_.end() - 1);
  45. return true;
  46. }
  47.  
  48. /** Get the front item from the deque. */
  49. int getFront() {
  50. if (isEmpty())
  51. return -1;
  52. return vector_.front();
  53. }
  54.  
  55. /** Get the last item from the deque. */
  56. int getRear() {
  57. if (isEmpty())
  58. return -1;
  59. return vector_.back();
  60. }
  61.  
  62. /** Checks whether the circular deque is empty or not. */
  63. bool isEmpty() {
  64. return vector_.empty();
  65. }
  66.  
  67. /** Checks whether the circular deque is full or not. */
  68. bool isFull() {
  69. return length_ == vector_.size();
  70. }
  71. };
  72.  
  73. /**
  74. * Your MyCircularDeque object will be instantiated and called as such:
  75. * MyCircularDeque* obj = new MyCircularDeque(k);
  76. * bool param_1 = obj->insertFront(value);
  77. * bool param_2 = obj->insertLast(value);
  78. * bool param_3 = obj->deleteFront();
  79. * bool param_4 = obj->deleteLast();
  80. * int param_5 = obj->getFront();
  81. * int param_6 = obj->getRear();
  82. * bool param_7 = obj->isEmpty();
  83. * bool param_8 = obj->isFull();
  84. */

406. 根据身高重建队列

  1. #include <vector>
  2. #include <algorithm>
  3.  
  4. class Solution {
  5. public:
  6. std::vector<std::vector<int>> reconstructQueue(std::vector<std::vector<int>>& people) {
  7. //1.排序
  8. std::sort(people.begin(), people.end(),
  9. [](std::vector<int> a, std::vector<int> b) {
  10. if (a[0] != b[0])
  11. return a[0] > b[0];
  12. return a[1] < b[1];
  13. });
  14.  
  15. //2.插入
  16. std::vector<std::vector<int>> res;
  17. for (auto p : people) {
  18. if (res.size() < p[1])
  19. res.push_back(p);
  20. if (res.size() >= p[1])
  21. res.insert(res.begin() + p[1], p);
  22. }
  23.  
  24. return res;
  25. }
  26. };

946. 验证栈序列

  1. #include <stack>
  2. #include <vector>
  3.  
  4. class Solution {
  5. private:
  6. std::stack<int> *stack_ = new std::stack<int>;
  7. public:
  8. bool validateStackSequences(std::vector<int>& pushed, std::vector<int>& popped) {
  9. int length = pushed.size();
  10. int j = 0;
  11.  
  12. for (int i = 0; i < length; ++i) {
  13. stack_->push(pushed[i]);
  14.  
  15. while (!stack_->empty() && stack_->top() == popped[j]) {
  16. j++;
  17. stack_->pop();
  18. }
  19. }
  20.  
  21. //return stack_->empty();
  22. return j == length;
  23. }
  24. };

笔记:bfs和dfs以及bfs衍生的层序遍历

https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/bfs-de-shi-yong-chang-jing-zong-jie-ceng-xu-bian-l/

bfs层次遍历二叉树代码:

  1. #include <vector>
  2. #include <queue>
  3.  
  4. //Definition for a binary tree node.
  5. struct TreeNode {
  6. int val;
  7. TreeNode *left;
  8. TreeNode *right;
  9. TreeNode() : val(0), left(nullptr), right(nullptr) {}
  10. TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  11. TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  12. };
  13.  
  14. class Solution {
  15. private:
  16. std::queue<TreeNode*> *queue_ = new std::queue<TreeNode*>;
  17. public:
  18. std::vector<std::vector<int>> levelOrder(TreeNode* root) {
  19. //bfs
  20. queue_->push(root);
  21.  
  22. while (!queue_->empty()) {
  23.  
  24. root = queue_->front();
  25. queue_->pop();
  26.  
  27. if (root->left != nullptr) {
  28. queue_->push(root->left);
  29. }
  30.  
  31. if (root->right != nullptr) {
  32. queue_->push(root->right);
  33. }
  34. }
  35.  
  36. }
  37. };

102. 二叉树的层序遍历

进一步,bfs衍生出层序遍历:

  1. #include <vector>
  2. #include <queue>
  3.  
  4. //Definition for a binary tree node.
  5. struct TreeNode {
  6. int val;
  7. TreeNode *left;
  8. TreeNode *right;
  9. TreeNode() : val(0), left(nullptr), right(nullptr) {}
  10. TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  11. TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  12. };
  13.  
  14. class Solution {
  15. private:
  16. std::queue<TreeNode*> *queue_ = new std::queue<TreeNode*>;
  17. public:
  18. std::vector<std::vector<int>> levelOrder(TreeNode* root) {
  19. //层序遍历
  20. std::vector<std::vector<int>> ret;
  21. if (root != nullptr)
  22. queue_->push(root);
  23.  
  24. while (!queue_->empty()) {
  25. int nodeNum = queue_->size();
  26. std::vector<int> vector;
  27. for (int i = 0; i < nodeNum; ++i) {
  28. root = queue_->front();
  29. queue_->pop();
  30.  
  31. vector.push_back(root->val);
  32.  
  33. if (root->left != nullptr) {
  34. queue_->push(root->left);
  35. }
  36. if (root->right != nullptr) {
  37. queue_->push(root->right);
  38. }
  39. }
  40.  
  41. ret.push_back(vector);
  42. }
  43.  
  44. return ret;
  45. }
  46. };

116. 填充每个节点的下一个右侧节点指针

  1. #include <vector>
  2. #include <queue>
  3.  
  4. // Definition for a Node.
  5. class Node {
  6. public:
  7. int val;
  8. Node* left;
  9. Node* right;
  10. Node* next;
  11.  
  12. Node() : val(0), left( nullptr), right( nullptr), next( nullptr) {}
  13.  
  14. Node(int _val) : val(_val), left( nullptr), right( nullptr), next( nullptr) {}
  15.  
  16. Node(int _val, Node* _left, Node* _right, Node* _next)
  17. : val(_val), left(_left), right(_right), next(_next) {}
  18. };
  19.  
  20. class Solution {
  21. private:
  22. std::queue<Node*> *queue_ = new std::queue<Node*>;
  23. public:
  24. Node* connect(Node* root) {
  25. //层序遍历
  26. if (root != nullptr)
  27. queue_->push(root);
  28.  
  29. while (!queue_->empty()) {
  30. int nodeNum = queue_->size();
  31.  
  32. for (int i = 0; i < nodeNum; ++i) {
  33. //注意这里的返回值不能是root,因为会更新root,导致结果不对
  34. //只需要更新原二叉树中响应位置的节点即可
  35. Node* temp = queue_->front();
  36. queue_->pop();
  37.  
  38. //连接,但是每层的最后一个节点不处理
  39. if (i < nodeNum - 1)
  40. temp->next = queue_->front();
  41.  
  42. if (temp->left != nullptr)
  43. queue_->push(temp->left);
  44. if (temp->right != nullptr)
  45. queue_->push(temp->right);
  46. }
  47. }
  48. return root;
  49. }
  50. };

61. 旋转链表

  1. #include <vector>
  2. #include <queue>
  3.  
  4. //Definition for singly-linked list.
  5. struct ListNode {
  6. int val;
  7. ListNode *next;
  8. ListNode() : val(0), next(nullptr) {}
  9. ListNode(int x) : val(x), next(nullptr) {}
  10. ListNode(int x, ListNode *next) : val(x), next(next) {}
  11. };
  12.  
  13. class Solution {
  14. public:
  15. ListNode* rotateRight(ListNode* head, int k) {
  16. if (head == nullptr || head->next == nullptr || k == 0)
  17. return head;
  18.  
  19. //求链表长度
  20. int length = 1;
  21. ListNode* tmp = head;
  22. while (tmp->next != nullptr) {
  23. tmp = tmp->next;
  24. length++;
  25. }
  26. int count = k % length;
  27. if (count == 0)
  28. return head;
  29.  
  30. tmp->next = head;//链表连接成环
  31.  
  32. for (int i = 0; i < length - count - 1; ++i) {
  33. head = head->next;
  34. }
  35.  
  36. ListNode* ret = head->next;
  37. head->next = nullptr;
  38.  
  39. return ret;
  40. }
  41. };

729. 我的日程安排表 I

  1. #include <map>
  2. #include <algorithm>
  3.  
  4. class MyCalendar {
  5. public:
  6. MyCalendar() {
  7.  
  8. }
  9.  
  10. bool book(int start, int end) {
  11. if (start >= end)
  12. return false;
  13.  
  14. //0.start 已重复
  15. if (map_.find(start) != map_.end())
  16. return false;
  17.  
  18. //1.首先插入
  19. map_.emplace(start, end);
  20.  
  21. //2.返回刚刚插入的迭代器位置
  22. auto pos = map_.find(start);
  23. //auto pos = map_.find(start).first;
  24.  
  25. //3.与(有序)map中的前后迭代器进行比较,根据比较结果决定保留或者删除
  26. //3.1 与前一个比较
  27. if (pos != map_.begin()) {
  28. --pos;//得到相邻的前一个迭代器 注意:因为map有序,所以这里默认的前一个迭代器的key < start
  29. if (pos->second > start) {
  30. //删除
  31. map_.erase(start);
  32. return false;
  33. }
  34. ++pos;
  35. }
  36.  
  37. //3.2 与后一个比较
  38. ++pos;//得到相邻的后一个迭代器,这里的后一个迭代器默认的key > start
  39. if (pos != map_.end()) {
  40. if (pos->first < end) {
  41. //删除
  42. map_.erase(start);
  43. return false;
  44. }
  45. }
  46.  
  47. return true;
  48. }
  49.  
  50. private:
  51. std::map<int, int> map_;
  52. };
  53.  
  54. /**
  55. * Your MyCalendar object will be instantiated and called as such:
  56. * MyCalendar* obj = new MyCalendar();
  57. * bool param_1 = obj.book(start,end);
  58. */

105. 从前序与中序遍历序列构造二叉树

  1. #include <vector>
  2. #include <unordered_map>
  3.  
  4. //Definition for a binary tree node.
  5. struct TreeNode {
  6. int val;
  7. TreeNode *left;
  8. TreeNode *right;
  9. TreeNode() : val(0), left(nullptr), right(nullptr) {}
  10. TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  11. TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  12. };
  13.  
  14. class Solution {
  15. public:
  16. TreeNode* buildTree(std::vector<int>& preorder, std::vector<int>& inorder) {
  17. int length = preorder.size();
  18.  
  19. for (int i = 0; i < length; ++i) {
  20. unorderedMap_[inorder[i]] = i;
  21. }
  22.  
  23. return mybuildTree(preorder, 0, length - 1, unorderedMap_, 0, length - 1);
  24. }
  25.  
  26. TreeNode* mybuildTree(std::vector<int>& preorder, int preLeft, int preRight,
  27. std::unordered_map<int, int>& map, int inLeft, int inRight) {
  28. //递归终止条件
  29. if (preLeft > preRight || inLeft > inRight)
  30. return nullptr;
  31.  
  32. //0.构建待返回的二叉树
  33. int rootVal = preorder[preLeft];
  34. TreeNode* root = new TreeNode(rootVal);
  35.  
  36. //1.得到根节点
  37. //注意:这里要用全局维护的唯一map!!!!!!!!!!!!!!!!!!!!!
  38. int pIndex = unorderedMap_[rootVal];
  39.  
  40. //2.构建左子树
  41. root->left = mybuildTree(preorder, preLeft + 1, pIndex - inLeft + preLeft, unorderedMap_, inLeft, pIndex -1);
  42.  
  43. //3.构建右子树
  44. root->right = mybuildTree(preorder, pIndex - inLeft + preLeft + 1, preRight, unorderedMap_, pIndex + 1, inRight);
  45.  
  46. return root;
  47. }
  48.  
  49. private:
  50. std::unordered_map<int, int> unorderedMap_;
  51. };

ps:后序和中序也能构造二叉树,代码如下:

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12.  
  13. /*这是后序和中序的代码!!!!!!!!!!!!!!!!!!!!!!!!!*/
  14. class Solution {
  15. private:
  16. std::unordered_map<int, int> map;
  17.  
  18. public:
  19. TreeNode* mybuildTree(std::vector<int>& bakorder, int bakLeft, int bakRight,
  20. std::unordered_map<int, int>& unorderedMap, int inLeft, int inRight) {
  21. //1.递归终止条件
  22. if (bakLeft > bakRight || inLeft > inRight)
  23. return nullptr;
  24.  
  25. int rootVal = bakorder[bakRight];
  26. TreeNode* root = new TreeNode(rootVal);
  27.  
  28. int pIndex = map[rootVal];
  29.  
  30. root->left = mybuildTree(bakorder, bakLeft, pIndex-1-inLeft+bakLeft,
  31. map, inLeft, pIndex-1);
  32.  
  33. root->right = mybuildTree(bakorder, pIndex-inLeft+bakLeft, bakRight-1,
  34. map, pIndex+1, inRight);
  35.  
  36. return root;
  37. }
  38.  
  39. TreeNode* buildTree(std::vector<int>& bakorder, std::vector<int>& inorder) {
  40. if (bakorder.size() != inorder.size())
  41. return nullptr;
  42.  
  43. int length = bakorder.size();
  44.  
  45. for (int i = 0; i < length; ++i) {
  46. map[inorder[i]] = i;
  47. }
  48.  
  49. return mybuildTree(bakorder, 0, length - 1, map, 0, length - 1);
  50. }
  51. };

112. 路径总和

  1. //Definition for a binary tree node.
  2. struct TreeNode {
  3. int val;
  4. TreeNode *left;
  5. TreeNode *right;
  6. TreeNode() : val(0), left(nullptr), right(nullptr) {}
  7. TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  8. TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  9. };
  10.  
  11. class Solution {
  12. public:
  13. bool hasPathSum(TreeNode* root, int targetSum) {
  14. if (root == nullptr)
  15. return false;
  16.  
  17. //递归终止条件
  18. if (root->left == nullptr && root->right == nullptr)
  19. return targetSum == root->val;
  20.  
  21. return hasPathSum(root->left, targetSum - root->val) or
  22. hasPathSum(root->right, targetSum - root->val);
  23. }
  24. };

98. 验证二叉搜索树

中序遍历方法:https://blog.csdn.net/qq_44179564/article/details/108696548

  1. #include <vector>
  2.  
  3. //Definition for a binary tree node.
  4. struct TreeNode {
  5. int val;
  6. TreeNode *left;
  7. TreeNode *right;
  8. TreeNode() : val(0), left(nullptr), right(nullptr) {}
  9. TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  10. TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  11. };
  12.  
  13. class Solution {
  14.  
  15. private:
  16. std::vector<int> vector;
  17. public:
  18. bool isValidBST(TreeNode* root) {
  19. if (root == nullptr)
  20. return false;
  21. inorder(root);
  22.  
  23. for (int i = 0; i < vector.size() - 1; ++i) {
  24. if (vector[i] >= vector[i + 1])
  25. return false;
  26. }
  27.  
  28. return true;
  29. }
  30.  
  31. void inorder(TreeNode* root) {
  32. if (root == nullptr)
  33. return;
  34. inorder(root->left);
  35. vector.push_back(root->val);
  36. inorder(root->right);
  37. }
  38. };

101. 对称二叉树

  1. //Definition for a binary tree node.
  2. struct TreeNode {
  3. int val;
  4. TreeNode *left;
  5. TreeNode *right;
  6. TreeNode() : val(0), left(nullptr), right(nullptr) {}
  7. TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  8. TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  9. };
  10.  
  11. class Solution {
  12. public:
  13. bool isSymmetric(TreeNode* root) {
  14. return check(root, root);
  15. }
  16.  
  17. bool check(TreeNode* r1, TreeNode* r2) {
  18. if (r1 == nullptr && r2 == nullptr)
  19. return true;
  20.  
  21. if (r1 == nullptr || r2 == nullptr)
  22. return false;
  23.  
  24. return r1->val == r2->val && check(r1->left, r2->right) && check(r1->right, r2->left);
  25. }
  26. };

102. 二叉树的层序遍历

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. private:
  14. std::queue<TreeNode*> *queue_ = new std::queue<TreeNode*>;
  15. public:
  16. std::vector<std::vector<int>> levelOrder(TreeNode* root) {
  17. //层序遍历
  18. std::vector<std::vector<int>> ret;
  19. if (root != nullptr)
  20. queue_->push(root);
  21.  
  22. while (!queue_->empty()) {
  23. int nodeNum = queue_->size();
  24. std::vector<int> vector;
  25. for (int i = 0; i < nodeNum; ++i) {
  26. root = queue_->front();
  27. queue_->pop();
  28.  
  29. vector.push_back(root->val);
  30.  
  31. if (root->left != nullptr) {
  32. queue_->push(root->left);
  33. }
  34. if (root->right != nullptr) {
  35. queue_->push(root->right);
  36. }
  37. }
  38.  
  39. ret.push_back(vector);
  40. }
  41.  
  42. return ret;
  43. }
  44. };

1047. 删除字符串中的所有相邻重复项

冗余代码思路,用两个栈解决:

  1. #include <string>
  2. #include <stack>
  3.  
  4. class Solution {
  5. private:
  6. std::stack<char> stack_;
  7. public:
  8. std::string removeDuplicates(std::string S) {
  9.  
  10. std::string ret;
  11.  
  12. for (auto s : S) {
  13. if (!stack_.empty() && stack_.top() == s) {
  14. stack_.pop();
  15. } else {
  16. stack_.push(s);
  17. }
  18. }
  19.  
  20. std::stack<char> tmp;
  21.  
  22. while (!stack_.empty()) {
  23. tmp.push(stack_.top());
  24. stack_.pop();
  25. }
  26.  
  27. while (!tmp.empty()) {
  28. ret += tmp.top();
  29. tmp.pop();
  30. }
  31.  
  32. return ret;
  33. }
  34. };

简洁代码,直接利用std::string本身就有的“栈特性”

  1. #include <string>
  2.  
  3. class Solution {
  4. public:
  5. std::string removeDuplicates(std::string S) {
  6.  
  7. std::string ret;
  8.  
  9. for (auto s : S) {
  10. if (!ret.empty() && ret.back() == s) {
  11. ret.pop_back();//弾栈操作
  12. } else {
  13. ret += s;
  14. }
  15. }
  16.  
  17. return ret;
  18. }
  19. };

1200. 最小绝对差

用stl里面的,可以允许key重复的multimap(注意这个map似乎没有重载[]插入的方式)

对于map:使用insert()插入元素的方式并不能覆盖掉相同key的值(跳过);而使用[]方式则可以覆盖掉之前的值

  1. #include <string>
  2. #include <vector>
  3. #include <map>
  4. #include <algorithm>
  5.  
  6. class Solution {
  7. public:
  8. std::vector<std::vector<int>> minimumAbsDifference(std::vector<int>& arr) {
  9.  
  10. std::sort(arr.begin(), arr.end());
  11.  
  12. for (int i = 0; i < arr.size() - 1; ++i) {
  13. std::vector<int> vector;
  14. vector.clear();
  15. vector.push_back(arr[i]);
  16. vector.push_back(arr[i + 1]);
  17. multimap_.insert(std::make_pair(std::abs(arr[i] - arr[i + 1]), vector));
  18. //multimap_[std::abs(arr[i] - arr[i + 1])] = vector;
  19. }
  20.  
  21. int flag = multimap_.begin()->first;
  22. std::vector<std::vector<int>> ret;
  23.  
  24. for (auto it = multimap_.begin(); it != multimap_.end(); ++it) {
  25. if (it->first > flag) {
  26. break;
  27. }
  28.  
  29. ret.push_back(it->second);
  30. }
  31.  
  32. return ret;
  33. }
  34.  
  35. private:
  36. std::multimap<int, std::vector<int>> multimap_;
  37. //std::map<int, std::vector<int>> map_;
  38. };

392. 判断子序列

  1. #include <string>
  2.  
  3. class Solution {
  4. public:
  5. bool isSubsequence(std::string s, std::string t) {
  6. int sLength = s.size();
  7. int tLength = t.size();
  8.  
  9. int i = 0;
  10. int j = 0;
  11.  
  12. while (i < sLength && j < tLength) {
  13. if (s[i] == t[j])
  14. i++;
  15. j++;
  16. }
  17.  
  18. return i == sLength;
  19. }
  20. };

1267. 统计参与通信的服务器

  1. #include <vector>
  2.  
  3. class Solution {
  4. public:
  5. int countServers(std::vector<std::vector<int>>& grid) {
  6. //行
  7. int m = grid.size();
  8. //列
  9. int n = grid[0].size();
  10.  
  11. //求每一行/列共有多少台服务器
  12. std::vector<int> count_m(m), count_n(n);
  13. for (int i = 0; i < m; ++i) {
  14. for (int j = 0; j < n; ++j) {
  15. if (grid[i][j] == 1) {
  16. count_m[i]++;
  17. count_n[j]++;
  18. }
  19. }
  20. }
  21.  
  22. //第二次遍历,求可通信服务器数量
  23. int ret = 0;
  24. for (int i = 0; i < m; ++i) {
  25. for (int j = 0; j < n; ++j) {
  26. //判断有效的条件
  27. if (grid[i][j] == 1 && (count_m[i] > 1 || count_n[j] > 1)) {
  28. ret++;
  29. }
  30. }
  31. }
  32.  
  33. return ret;
  34. }
  35. };

剑指 Offer 33. 二叉搜索树的后序遍历序列

  1. #include <vector>
  2.  
  3. class Solution {
  4. public:
  5. /*
  6. * 1.后序遍历: 左、右、根
  7. * 2.二叉搜索树:左子树所有节点的值 < 根节点的值;
  8. * 右子树所有节点的值 > 根节点的值*/
  9. bool verifyPostorder(std::vector<int>& postorder) {
  10.  
  11. return help(postorder, 0, postorder.size() - 1);
  12. }
  13.  
  14. bool help(std::vector<int>& postorder, int i, int j) {
  15. //递归终止条件:整个二叉树遍历完了
  16. if (i >= j)
  17. return true;
  18. //利用指针p,试图: 任务1.区分左右子树;任务2.遍历完这一次递归的整个树
  19. int p = i;
  20. while (postorder[p] < postorder[j]) {
  21. p++;
  22. }
  23. //找到了右子树,任务1完成
  24. int m = p;
  25. while (postorder[p] > postorder[j]) {
  26. p++;
  27. }
  28. //遍历完了这一次递归的整个树,任务2完成
  29.  
  30. //继续递归,分别判断左子树和右子树
  31. return j == p && help(postorder, i, m -1) && help(postorder, m, j-1);
  32. }
  33. };

300. 最长递增子序列

  1. #include <vector>
  2. #include <algorithm>
  3.  
  4. class Solution {
  5. public:
  6. int lengthOfLIS(std::vector<int>& nums) {
  7. int n = nums.size();
  8. if (n == 0)
  9. return 0;
  10.  
  11. std::vector<int> dp(n ,1);
  12.  
  13. for (int i = 0; i < n; ++i) {
  14. for (int j = 0; j < i; ++j) {
  15. if (nums[j] < nums[i]) {
  16. dp[i] = std::max(dp[i], dp[j] + 1);
  17. }
  18. }
  19. }
  20.  
  21. return *std::max_element(dp.begin(), dp.end());
  22.  
  23. }
  24. };

c++刷leetcode记录的更多相关文章

  1. 用golang刷LeetCode

    用golang刷LeetCode 用Go语言刷LeetCode记录,只是为了练习Go语言,能力有限不保证都是最优解,只能在此抛转引玉了. 数据结构和算法 数据结构和算法是程序员的命根子,没了命根子也就 ...

  2. LeetCode刷题记录(python3)

    由于之前对算法题接触不多,因此暂时只做easy和medium难度的题. 看完了<算法(第四版)>后重新开始刷LeetCode了,这次决定按topic来刷题,有一个大致的方向.有些题不止包含 ...

  3. leetcode刷题记录--js

    leetcode刷题记录 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但 ...

  4. Leetcode刷题记录(python3)

    Leetcode刷题记录(python3) 顺序刷题 1~5 ---1.两数之和 ---2.两数相加 ---3. 无重复字符的最长子串 ---4.寻找两个有序数组的中位数 ---5.最长回文子串 6- ...

  5. 刷leetcode是什么样的体验?【转】

    转自:https://www.zhihu.com/question/32322023 刷leetcode是什么样的体验? https://leetcode.com/ 1 条评论   默认排序 按时间排 ...

  6. GitHub 热点速览 Vol.18:刷 LeetCode 的正确姿势

    作者:HelloGitHub-小鱼干 摘要:找对路子,事半功倍,正如本周 GitHub Trending #刷 LeetCode# 主题想表达的那般,正确的学习姿势方能让人走得更远,走进大厂

  7. 刷LeetCode的简易姿势

    近期抽空刷了刷LeetCode,算是补补课. 由于不是很习惯直接在网页上Coding&Debug,所以还是在本地环境下进行编码调试,觉得基本OK后再在网页上提交. 主要采用Python3进行提 ...

  8. 【算法】数据结构与算法基础总览(中)——刷Leetcode等算法题时一些很实用的jdk辅助方法锦集

    最近重新学习数据结构与算法以及刷leetcode算法题时,发现不少jdk自带的方法可以提升刷题的效率.这些小技巧不仅仅对刷算法题带来便利,对我们平时开发也是很有帮助的.本文以java语言为基础,记录了 ...

  9. 用 JavaScript 刷 LeetCode 的正确姿势【进阶】

    之前写了篇文章 用JavaScript刷LeetCode的正确姿势,简单总结一些用 JavaScript 刷力扣的基本调试技巧.最近又刷了点题,总结了些数据结构和算法,希望能对各为 JSer 刷题提供 ...

随机推荐

  1. 阅读笔记——长文本匹配《Matching Article Pairs with Graphical Decomposition and Convolutions》

    论文题目:Matching Article Pairs with Graphical Decomposition and Convolutions 发表情况:ACL2019 腾讯PCG小组 模型简介 ...

  2. 深入学习python内存管理

    深入Python的内存管理   作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 语言的内存管理是语言设计的一个重要方面.它是决定语 ...

  3. Ubuntu安装盘的制作

    准备工作 Ubuntu系统镜像 win32diskimager U盘(4G以上),对重要文件提前备份 制作 下载系统镜像 进入官网 我们下载的版本是18.04,不是20.04 在页面中,找到BitTo ...

  4. 我在 Gitee 上发现了一个简洁又好用的网络音乐播放器!

    这几天无聊的时候我想听听歌,但我想要找一个简单快速的网络音乐播放器来用用.这时我在 Gitee 上看见一个看上去不错的开源项目 -- Hi音乐. 项目链接:https://gitee.com/hi-j ...

  5. CF1581

    其实是手速场,但因为 \(\rm D, E\) 数据范围时限太阴间卡住了. D \(\rm Hint:\) 本题常数极小加适当剪枝可以 \(\mathcal{O}(n ^ 5)\) 过 \(100\) ...

  6. [USACO18DEC]Balance Beam P

    根据题意不难发现这个模型是不好进行贪心的,于是可以考虑使用 \(dp\).可以令 \(dp_i\) 表示在 \(i\) 位置以最优策略能获得的报酬期望值,那么会有转移: \[dp_i = \max(f ...

  7. JavaIO 思维导图

    网络搜集,万分感谢!

  8. CSS 3D的魅力

    用户1093975发表于Web项目聚集地订阅 151 在这篇文章中: 前言: demo1 demo2 结语: 本文介绍了CSS来实现3D效果,并且有详细代码和解释.建议大家只字不差的阅读.本文的作者是 ...

  9. java代码注意点总结(持续更新)

    1. if(username.equals("zxx")){} 这样写的话,如果username是null, 则会报NullPointerException,所以先要判断usern ...

  10. Java--面向对象设计

    [转载自本科老师上课课件] 问题一: 在一个软件的功能模块中,需要一种图像处理的功能.该图像处理的策略(如何处理)与图像的内容是相关的.如:卫星的运行图片,使用策略A处理方式,如果是卫星内云图片,则需 ...