面试常用基础算法

目录

快速排序

#include <iostream>
#include <algorithm>using namespace std;const int N = 1e5 + 10;int n;
int arr[N];void quick_sort(int l, int r) {if (l >= r) return;int mid = l + r >> 1;int val = arr[mid];int p1 = l - 1, p2 = r + 1;while (p1 < p2) {while (arr[++p1] < val);while (arr[--p2] > val);if (p1 < p2) swap(arr[p1], arr[p2]);}quick_sort(l, p2);quick_sort(p2 + 1, r);
}int main() {cin >> n;for (int i = 0; i < n; ++i) cin >> arr[i];quick_sort(0, n - 1);for (int i = 0; i < n; ++i) cout << arr[i] << " ";cout << "\n";return 0;
}

归并排序

#include <iostream>
#include <algorithm>using namespace std;const int N = 1e5 + 10;int n;
int arr[N], tmp[N];void merge_sort(int l, int r) {if (l >= r) return;int mid = l + r >> 1;merge_sort(l, mid);merge_sort(mid + 1, r);int i = l, j = mid + 1, k = 0;while (i <= mid && j <= r) {if (arr[i] <= arr[j]) tmp[k++] = arr[i++];else tmp[k++] = arr[j++];}while (i <= mid) tmp[k++] = arr[i++];while (j <= r) tmp[k++] = arr[j++];for (i = l; i <= r; ++i) arr[i] = tmp[i - l];
}int main() {cin >> n;for (int i = 0; i < n; ++i) cin >> arr[i];merge_sort(0, n - 1);for (int i = 0; i < n; ++i) cout << arr[i] << " ";cout << "\n";return 0;
}

堆排序

#include <iostream>
#include <algorithm>using namespace std;const int N = 1e5 + 10;int n, k;
int heap[N], sz;void down(int u) {int t = u;int ls = u << 1;int rs = u << 1 | 1;if (ls <= sz && heap[ls] <= heap[t]) t = ls;if (rs <= sz && heap[rs] <= heap[t]) t = rs;if (t != u) {swap(heap[u], heap[t]);down(t);}
}int main() {ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);cin >> n >> k;for (int i = 1; i <= n; ++i) cin >> heap[i];sz = n;for (int i = n >> 1; i >= 1; --i) down(i);while (k--) {int res = heap[1];cout << res << " ";swap(heap[1], heap[sz--]);down(1);}return 0;
}

n n n皇后问题

#include <iostream>
#include <algorithm>
#include <cstring>using namespace std;const int N = 10;int n;
char g[N][N];bool is_valid(int x, int y) {for (int i = 0; i < n; ++i) if (g[i][y] == 'Q') return false;for (int i = 0; i < n; ++i) if (g[x][i] == 'Q') return false;int nx = x, ny = y;while (nx >= 0 && ny >= 0) {if (g[nx][ny] == 'Q') return false;nx--, ny--;}nx = x, ny = y;while (nx < n && ny >= 0) {if (g[nx][ny] == 'Q') return false;nx++, ny--;}nx = x, ny = y;while (nx >= 0 && ny < n) {if (g[nx][ny] == 'Q') return false;nx--, ny++;}nx = x, ny = y;while (nx < n && ny < n) {if (g[nx][ny] == 'Q') return false;nx++, ny++;}return true;
}void dfs(int row, int k) {if (k == 0) {for (int i = 0; i < n; ++i) {for (int j = 0; j < n; ++j) {cout << g[i][j];}cout << "\n";}cout << "\n";return;}// 枚举列for (int i = 0; i < n; ++i) {if (is_valid(row, i)) {g[row][i] = 'Q';dfs(row + 1, k - 1);g[row][i] = '.';}}
}int main() {cin >> n;for (int i = 0; i < n; ++i) {for (int j = 0; j < n; ++j) {g[i][j] = '.';}}dfs(0, n);return 0;
}

最大和子数组

53.最大和子数组

class Solution {
public:int maxSubArray(vector<int>& nums) {const int N = 1e5 + 10;int arr[N];int f[N];int n = nums.size();for (int i = 0; i < n; ++i) {arr[i + 1] = nums[i];}memset(f, -0x3f, sizeof f);int res = -0x3f3f3f3f;arr[0] = 0;for (int i = 1; i <= n; ++i) {f[i] = max(arr[i], f[i - 1] + arr[i]);res = max(res, f[i]);}return res;}
};

爬楼梯

class Solution {
public:int climbStairs(int n) {const int N = 46;int f[N] = {0};f[0] = 1;f[1] = 1;for (int i = 2; i <= n; ++i) f[i] = f[i - 1] + f[i - 2];return f[n];}
};

中心扩展法求最长回文子序列

516. 最长回文子序列

采用中心扩展法, 分别枚举所有可能的回文串的中心位置
然后再将回文串长度的类别分为奇数偶数, 分别统计答案

#include <string>
using namespace std;class Solution {
public:int countSubstrings(string s) {int res = 0;int n = s.size();for (int i = 0; i < n; ++i) {int l = i, r = i;while (l >= 0 && r < n && s[l--] == s[r++]) res++;l = i, r = i + 1;while (l >= 0 && r < n && s[l--] == s[r++]) res++;}return res;}
};

分割回文串

131.分割回文串

先用DP预处理所有合法的子串, 然后DFS所有分割方式

#include <iostream>
#include <vector>
#include <cstring>using namespace std;class Solution {
public:const int N = 20;bool f[20][20];void dfs(string &str, vector<vector<string>> &res, vector<string> &tmp, int u) {if (u >= str.size()) {res.push_back(tmp);return;}for (int v = u; v < str.size(); ++v) {if (f[u][v]) {tmp.push_back(str.substr(u, v - u + 1));dfs(str, res, tmp, v + 1);tmp.pop_back();}}}vector<vector<string>> partition(string s) {memset(f, false, sizeof f);int n = s.size();// 预处理回文子串for (int i = 0; i < n; ++i) {f[i][i] = true;if (i + 1 < n && s[i] == s[i + 1]) {f[i][i + 1] = true;}}for (int len = 3; len <= n; ++len) {for (int i = 0; i + len - 1 < n; ++i) {int j = i + len - 1;if (s[i] == s[j] && f[i + 1][j - 1]) {f[i][j] = true;}}}vector<vector<string>> res;vector<string> tmp;dfs(s, res, tmp, 0);return res;}
};

动态规划求最长回文子序列

516.最长回文子序列

class Solution {
public:int longestPalindromeSubseq(string s) {const int N = 1010;int f[N][N] = {0};int n = s.size();for (int i = 0; i < n; ++i) f[i][i] = 1;for (int len = 2; len <= n; ++len) {for (int i = 0; i + len - 1 < n; ++i) {int j = i + len - 1;if (s[i] == s[j]) f[i][j] = f[i + 1][j - 1] + 2;else f[i][j] = max(f[i + 1][j], f[i][j - 1]);}}return f[0][n - 1];}
};

最长回文子串

5.最长回文子串

动态规划预处理每个状态是否是合法的, 同时记录最长的回文字符串

class Solution {
public:string longestPalindrome(string s) {const int N = s.size() + 10;bool f[N][N];memset(f, false, sizeof f);int n = s.size();for (int i = 0; i < n; ++i) f[i][i] = true;int start = 0, sz = 1;for (int i = 0; i < n; ++i) {int j = i + 1;if (s[i] == s[j]) {f[i][j] = true;start = i, sz = 2;}}for (int len = 3; len <= n; ++len) {for (int i = 0; i + len - 1 < n; ++i) {int j = i + len - 1;if (s[i] == s[j] && f[i + 1][j - 1]) {f[i][j] = true;if (j - i + 1 > sz) {sz = j - i + 1;start = i;}}}}string res = "";for (int i = start; i < start + sz; ++i) res += s[i];return res;}
};

单调栈

42.接雨水

栈底到栈顶的存储的柱子高度是递减的, 当新加入的柱子高度大于当前栈顶的高度的时候, 说明能够形成凹槽, 然后边弹栈边计算积水面积

class Solution {
public:int trap(vector<int>& height) {const int N = height.size() + 10;int stack[N], top = 0;int res = 0;for (int i = 0; i < height.size(); ++i) {int val = height[i];while (top && val > height[stack[top]]) {int pre = stack[top--];if (!top) break;// 计算两个柱子之间的距离int d = i - stack[top] - 1;// 减去凹槽的高度int h = min(height[stack[top]], height[i]) - height[pre];res += h * d;}stack[++top] = i;}return res;}
};

双指针算法

C - Shortest Duplicate Subarray

问题陈述
给你一个正整数
N N N 和一个长度为 N N N 的整数序列
请判断 A A A 是否存在一个非空(连续)子数组,它有一个重复值,多次出现在 A A A 中。如果存在这样的子数组,求最短的子数组的长度。

维护滑动窗口, 使用 s e t set set记录是否有重复元素, 如果有重复元素缩短左侧窗口, 直到没有重复元素, 然后递增右侧窗口

#include <iostream>
#include <algorithm>
#include <cstring>
#include <unordered_set>using namespace std;const int N = 2e5 + 10, INF = 0x3f3f3f3f;int n, arr[N];
unordered_set<int> s;int main() {ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);cin >> n;for (int i = 0; i < n; ++i) cin >> arr[i];int res = INF;int l = 0;for (int r = 0; r < n; ++r) {while (s.count(arr[r])) {res = min(res, r - l + 1);s.erase(arr[l++]);}s.insert(arr[r]);}if (res == INF) res = -1;cout << res << endl;return 0;
}

11. 盛最多水的容器

贪心策略: 定义两个指针指向两侧, 每次移动高度较小的那个指针, 这样能够围成的面积有可能变大

class Solution {
public:int maxArea(vector<int>& height) {int res = 0;int l = 0, r = height.size() - 1;while (l < r) {int h = min(height[l], height[r]);res = max(res, h * (r - l));height[l] < height[r] ? l++ : r--;}return res;}
};

LCR 179. 查找总价格为目标值的两个商品

class Solution {
public:vector<int> twoSum(vector<int>& price, int target) {int l = 0, r = price.size() - 1;vector<int> res;while (l < r) {int sum = price[l] + price[r];if (sum == target) {res.push_back(price[l]);res.push_back(price[r]);break;}else if (sum < target) l++;else r--;}return res;}
};

链表中的中间节点

class Solution {
public:ListNode* middleNode(ListNode* head) {//		定义快慢指针, 快指针走到终点, 慢指针走到中间ListNode *u = head;ListNode *v = head;while (u != nullptr) {if (u->next == nullptr) break;u = (u->next)->next;v = v->next;}return v;}
};

判断链表中是否含有环

class Solution {
public:bool hasCycle(ListNode *head) {ListNode *u = head;ListNode *v = head;while (u != nullptr && v != nullptr) {if (u->next == nullptr) break;u = u->next->next;v = v->next;if (u == v) return true;}return false;}
};

寻找链表中倒数第k个位置

class Solution {
public:ListNode* trainingPlan(ListNode* head, int cnt) {ListNode *u = head;ListNode *v = head;cnt--;while (cnt--) u = u->next;while (u->next != nullptr) {u = u->next;v = v->next;}return v;}
};

392. 判断子序列

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>using namespace std;class Solution {
public:bool isSubsequence(string s, string t) {int i = 0, j = 0;int n = s.size(), m = t.size();if (n == 0) return true;while (i < n && j < m) {if (s[i] == t[j]) {if (i == n - 1) {cout << i << endl;return true;}i++;}j++;}return false;}
};

将所有0移动到数组末尾, 同时保证剩余元素相对位置不变

class Solution {
public:void moveZeroes(vector<int>& nums) {int n = nums.size();
//		i是处理好的下一个位置, j遍历整个数组int i = 0, j = 0;while (j < n) {if (nums[j]) {swap(nums[i], nums[j]);i++;}j++;}}
};

修改 + 分割回文串

1278. 分割回文串 III

f [ i ] [ j ] f[i][j] f[i][j]代表考虑前 i i i个字符并且已经分割了 j j j个回文子串的所有方案的集合

属性: 修改的最少字符

如何进行集合划分/状态转移
考虑第 j j j个回文子串的起始位置 i 0 i_0 i0
f [ i ] [ j ] = m i n ( f [ i 0 ] [ j − 1 ] + c o s t ( S , i 0 + 1 , i ) ) f[i][j] = min(f[i_0][j - 1] + cost(S, i_0 + 1, i)) f[i][j]=min(f[i0][j1]+cost(S,i0+1,i))
时间复杂度: O ( n 3 k ) O(n ^ 3k) O(n3k)

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>using namespace std;const int N = 110;int n;
//f[i][j]考虑前i个字符, 已经分割了j个子串的最小修改字符次数
int f[N][N];class Solution {
public:
//	计算将l到r修改为回文串需要的最小代价int cost(string &s, int l, int r) {int res = 0;for (int i = l, j = r; i < j; ++i, --j) {if (s[i] != s[j]) res++;}return res;}int palindromePartition(string s, int k) {n = s.size();memset(f, 0x3f, sizeof f);f[0][0] = 0;for (int i = 1; i <= n; ++i) {for (int j = 1; j <= min(i, k); ++j) {
//				如果只分割了一个子串, 那么就是从开头到当前位置if (j == 1) f[i][j] = cost(s, 0, i - 1);
//				枚举最后一个回文子串的起始位置else {for (int l = j - 1; l < i; ++l) {f[i][j] = min(f[i][j], f[l][j - 1] + cost(s, l, i - 1));}}}}return f[n][k];}
};

滑动窗口

1004. 最大连续1的个数 III

class Solution {
public:int longestOnes(vector<int>& nums, int k) {int n = nums.size();int l = 0, r = 0;int res = 0;int cnt = 0;while (r < n) {if (nums[r] == 0) cnt++;while (cnt > k) {if (nums[l] == 0) cnt--;l++;}res = max(res, r - l + 1);r++;}return res;}
};

替换后最长重复字符

class Solution {
public:int characterReplacement(string s, int k) {int n = s.size();int l = 0, r = 0;
//		记录每个字符出现的次数int cnt[26] = {0};int max_cnt = 0;int res = 0;while (r < n) {cnt[s[r] - 'A']++;max_cnt = max(max_cnt, cnt[s[r] - 'A']);if (r - l + 1 - max_cnt > k) {cnt[s[l] - 'A']--;l++;}res = max(res, r - l + 1);r++;}return res;}
};

2024. 考试的最大困扰度

class Solution {
public:int get(char c) {if (c == 'F') return 0;return 1;}int maxConsecutiveAnswers(string answerKey, int k) {int n = answerKey.size();int l = 0, r = 0;int cnt[2] = {0};int max_cnt = 0;int res = 0;while (r < n) {int &val = cnt[get(answerKey[r])];val++;max_cnt = max(max_cnt, val);if (r - l + 1 - max_cnt > k) {cnt[get(answerKey[l])]--;l++;}res = max(res, r - l + 1);r++;}return res;}
};

395. 至少有 K 个重复字符的最长子串

外层枚举的是不同字符的种类

class Solution {
public:int longestSubstring(string s, int k) {int n = s.size();int res = 0;for (int i = 1; i <= 26; ++i) {int cnt[26] = {0};int l = 0, r = 0;int type_cnt = 0;int tmp = 0;while (r < n) {
//				当前窗口中字符类型数量小于等于iif (type_cnt <= i) {int u = s[r] - 'a';if (cnt[u] == 0) type_cnt++;cnt[u]++;if (cnt[u] == k) tmp++;r++;}
//				当前窗口字符数量大于i, 缩小窗口else {int u = s[l] - 'a';if (cnt[u] == k) tmp--;cnt[u]--;if (cnt[u] == 0) type_cnt--;l++;}if (type_cnt == i && tmp == i) res = max(res, r - l);}}return res;}
};

713. 乘积小于 K 的子数组

class Solution {
public:int numSubarrayProductLessThanK(vector<int>& nums, int k) {if (k <= 1) return 0;int n = nums.size();int l = 0, r = 0;int res = 0;int curr = 1;while (r < n) {curr *= nums[r];while (curr >= k) {curr /= nums[l];l++;}
//			以r结尾的子数组的数量res += r - l + 1;r++;}return res;}
};

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

class Solution {
public:string removeDuplicates(string s) {string res = "";for (char c : s) {if (!res.empty() && res.back() == c) res.pop_back();else res.push_back(c);}return res;}
};

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/79778.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

相对路径和绝对路径解析

在 Linux/Unix 和文件系统中&#xff0c;绝对路径和相对路径是描述文件或目录位置的两种方式&#xff0c;它们的核心区别在于路径的起点和使用场景。以下是详细对比&#xff1a; 目录 1. 定义与起点 2. 符号与语法 3. 使用场景 4. 实际示例 示例 1&#xff1a;定位文件 示…

【算法数据结构】leetcode37 解数独

37. 解数独 - 力扣&#xff08;LeetCode&#xff09; 题目描述&#xff1a; 题目要求每一行 &#xff0c;每一列&#xff0c;每个3*3 的子框只能出现一次。每个格子的数字范围1-9. 需要遍历每个空格填入可能的数字&#xff0c;并验证符合规则。如果符合就填入&#xff0c;不符…

Vector的学习

vector简介 vector的相关文档对于想深入了解的同学可以参考这个文档进行学习。 vector是表示可变大小数组的序列容器。 就像数组一样&#xff0c;vector也采用的连续存储空间来存储元素。也就是意味着可以采用下标对vector的元素进行访问&#xff0c;和数组一样高效。但是又不…

Vue常用指令入门

1. v-for 作用&#xff1a;用于遍历对象或数组 注意&#xff1a;需要提供key属性&#xff0c;可以提高性能和避免渲染错误&#xff0c;值通常为index或item.id <li v-for"(item, index) in items" :key"index">{{ item }} </li>2. v-if,v-el…

在机器视觉检测中为何选择线阵工业相机?

线阵工业相机&#xff0c;顾名思义是成像传感器呈“线”状的。虽然也是二维图像&#xff0c;但极宽&#xff0c;几千个像素的宽度&#xff0c;而高度却只有几个像素的而已。一般在两种情况下使用这种相机&#xff1a; 1. 被测视野为细长的带状&#xff0c;多用于滚筒上检测的问…

线性DP:最长上升子序列(子序列可不连续,子数组必须连续)

目录 Q1&#xff1a;简单遍历 Q2&#xff1a;变式&#xff08;加大数据量&#xff09; Q1&#xff1a;简单遍历 Dp问题 状态表示 f(i,j) 集合所有以第i个数结尾的上升子序列集合-f(i,j)的值存的是什么序列长度最大值max- 状态计算 &#xff08;其实质是集合的划分&#xff09;…

【Web前端技术】第二节—HTML标签(上)

hello&#xff01;好久不见—— 做出一个属于自己的网站&#xff01; 云边有个稻草人-个人主页 Web前端技术—本篇文章所属专栏 目录 一、HTML 语法规范 1.1 基本语法概述 1.2 标签关系 二、HTML 基本结构标签 2.1 第一个 HTML 网页 2.2 基本结构标签总结 三、网页开发…

论文降重GPT指令-实侧有效从98%降低到8%

步骤1&#xff1a;文本接收 指令&#xff1a; 请用户提供需要优化的文本内容。 对文本进行初步分析&#xff0c;识别文本的基本结构和风格。 操作&#xff1a; 接收并分析用户提交的文本。 步骤2&#xff1a;文本优化 2.1 连接词处理 指令&#xff1a; 删除或替换连接词&#x…

Jsp技术入门指南【九】详细讲解JSTL

Jsp技术入门指南【九】详细讲解JSTL 前言一、什么是JSTL&#xff1f;&#xff08;JavaServer Pages Standard Tag Library&#xff09;二、使用JSTL前的准备三、核心标签库常用标签详解1. <c:out>&#xff1a;输出内容&#xff08;替代<% %>&#xff09;2. <c:i…

Linux操作系统--进程的创建和终止

目录 1.进程创建 1.1fork()函数初识 1.2写时拷贝 1. 提升系统效率 2. 隔离错误影响 3. 支持并行计算 2.进程终止&#xff1a; 2.1进程退出场景&#xff1a; 2.2进程常见退出方法&#xff1a; 2.3_exit()系统调用接口 2.4exit函数 2.5return退出 1.进程创建 1.1for…

OSPF综合实验——企业边界路由器、LSA收敛

IP划分粗略记号&#xff0c;方便后续配置 配置IP和环回--->ISP的IP配置和cheat认证---->配置OSPF和RIP---->企业边界路由网段汇总---->特殊区域---> 缺省路由&#xff0c;重分发---->nat配置---->实现全网通 路由器配置IP和环回地址 <Huawei>sys…

Java【网络原理】(4)HTTP协议

目录 1.前言 2.正文 2.1自定义协议 2.2HTTP协议 2.2.1抓包工具 2.2.2请求响应格式 2.2.2.1URL 2.2.2.2urlencode 2.2.3认识方法 2.2.3.1GET与POST 2.2.3.2PUT与DELETE 2.2.4请求头关键属性 3.小结 1.前言 哈喽大家好啊&#xff0c;今天来继续给大家带来Java中网络…

Android学习总结之APK打包流程

一、预处理阶段&#xff08;编译前准备&#xff09; 1. AIDL 文件处理&#xff08;进程间通信基础&#xff09; 流程&#xff1a; 用于实现 Android 系统中不同进程间的通信&#xff08;IPC&#xff09;。在项目构建时&#xff0c;AIDL 编译器会将 .aidl 文件编译为 Java 接口…

BDO分厂积极开展“五个一”安全活动

BDO分厂为规范化学习“五个一”活动主题&#xff0c;按照“上下联动、分头准备 、差异管理、资源共享”的原则&#xff0c;全面激活班组安全活动管理新模式&#xff0c;正在积极开展班组安全活动&#xff0c;以单元班组形式对每个班组每周组织一次“五个一”安全活动。 丁二醇单…

【音视频】FLV格式分析

FLV概述 FLV(Flash Video)是Adobe公司推出的⼀种流媒体格式&#xff0c;由于其封装后的⾳视频⽂件体积⼩、封装简单等特点&#xff0c;⾮常适合于互联⽹上使⽤。⽬前主流的视频⽹站基本都⽀持FLV。采⽤FLV格式封装的⽂件后缀为.flv。 FLV封装格式是由⼀个⽂件头(file header)和…

Java表达式1.0

Java开发工具 在当今的Java开发领域&#xff0c;IntelliJ IDEA已然成为了众多开发者心目中的首选利器&#xff0c;它被广泛认为是目前Java开发效率最快的IDE工具。这款备受瞩目的开发工具是由JetBrains公司精心打造的&#xff0c;而JetBrains公司总部位于风景如画的捷克共和国首…

Map遍历

第一种遍历方式键找值&#xff1a; 增强for循环&#xff1a; 通过获取元素中的键&#xff0c;get到对应的值&#xff0c;通过增强for循环获取集合里的键&#xff0c;然后用get方法通过键获取值 代码演示&#xff1a; import java.text.ParseException; import java.util.*;…

内网穿透服务器—FRP

某天某刻空闲的时候跟同事聊的本地的存储服务如果我想让其他公网内的用户使用&#xff08;这个存储服务只是一个临时文件传递站&#xff0c;碎文件&#xff0c;安全低的&#xff09;&#xff0c;然后我们就探讨到了FRP一个比较久远的技术&#xff0c;来做内网穿透&#xff0c;下…

力扣每日打卡16 781. 森林中的兔子(中等)

力扣 781. 森林中的兔子 中等 前言一、题目内容二、解题方法1. 哈希函数&#xff08;来自评论区大佬的解题方法&#xff09;2.官方题解2.1 方法一&#xff1a;贪心 前言 这是刷算法题的第十六天&#xff0c;用到的语言是JS 题目&#xff1a;力扣 781. 森林中的兔子 (中等) 一、…

基于深度学习的线性预测:创新应用与挑战

一、引言 1.1 研究背景 深度学习作为人工智能领域的重要分支&#xff0c;近年来在各个领域都取得了显著的进展。在线性预测领域&#xff0c;深度学习也逐渐兴起并展现出强大的潜力。传统的线性预测方法在处理复杂数据和动态变化的情况时往往存在一定的局限性。而深度学习凭借…