当前位置: 首页 > news >正文

8.20刷题笔记

215.数组中的第K个最大元素

class Solution {
public:int findKthLargest(vector<int>& nums, int k) {std::priority_queue<int, vector<int>, std::greater<int>> minHeap;for (int i = 0; i < k; i++) {minHeap.push(nums[i]);}for (int i = k; i < nums.size(); i++) {if (minHeap.top() < nums[i]) {minHeap.pop();minHeap.push(nums[i]);}}return minHeap.top();}
}

300.最长递增子序列

class Solution {
public:int lengthOfLIS(vector<int>& nums) {if (nums.empty()) return 0;vector<int> dp(nums.size(), 1);int maxLength = 1;for (int i = 0; i < nums.size(); i++) {for (int j = 0; j < i; j++) {if (nums[j] < nums[i]) {dp[i] = max(dp[i], dp[j] + 1);}}}return maxLength;}
}

912.排序数组

class Solution {
public: vector<int> sortArray(vector<int>& nums) {randomized_quickSort(nums, 0, nums.size() - 1);return nums;}void randomized_quickSort(vector<int>& nums, int low, int high) {if (low < high) {int pivotIndex = randomized_partition(nums, low, high);randomized_quickSort(nums, low, pivotIndex - 1);randomized_quickSort(nums, pivotIndex + 1, high);}}int randomized_partition(vector<int>& nums, int low, int high) {int i = rand() % (high - low + 1) + low;std::swap(nums[high], nums[i]);return partition(nums, low, high);}int partition(vector<int>& nums, int low, int high) {int pivot = nums[high];int i = low - 1;for (int j = low; j < high; j++) {if (nums[j] < pivot) {i++;std::swap(nums[i], nums[j]);}}std::swap(nums[i + 1], nums[high]);return i + 1;}
}

572.另一棵树的子树

class Solution {
public:bool isSubtree(TreeNode* root, TreeNode* subRoot) {if (!root) return false;bool isMatch = checktree(root, subRoot);if (!isMatch) {isMatch = isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);}return isMatch;}bool checktree(TreeNode* root, TreeNode* subRoot) {if (!root && !subRoot) return true;if ((!root && subRoot) || (root && !subRoot) || root->val != subRoot->val) {return false;}return checktree(root->left, subRoot->left) && checktree(root->right, subRoot->right);}
};

53.最大子数组和

class Solution {
public:int maxSubArray(vector<int>& nums) {int n = nums.size();int maxsum = nums[0];int pre = 0;for (int i = 0; i < n; i++) {pre = max(nums[i], pre + nums[i]);maxsum = max(maxsum, pre);}return maxsum;}
}

http://www.mrgr.cn/news/2218.html

相关文章:

  • SQL学习五大步骤
  • 可复制拖拽流程图
  • AI 进阶实战 | 走进大模型(LLM)+智能体(Agent)+提示词(Prompt)
  • 深度学习基础—Batch Norm
  • PMP考试不用慌,收下这份备考指南(附PMP学习资料包)
  • Tomcat部署项目get请求中文乱码
  • 为什么apple email的邮件显示不全
  • avx2 计算一个uint8_t数组的平方加速
  • react中 useContext 和useReducer的使用
  • RabbitMQ环境搭建
  • 【Vue3】编程式路由导航
  • React学习笔记(一)——react基础
  • 存储和传输/寻找大端字节序/有哪款MCU或MPU是真支持大端?
  • I/O模型
  • C++ IO流
  • 特洛伊木马:现代网络安全的隐形威胁
  • Matplotlib库学习之scatter(模块)
  • 【LeetCode热题100】双指针
  • 微信小程序蓝牙函数流程图
  • 鸿蒙内核源码分析(时钟任务篇)