华为实习机试
递归:LeetCode70、112、509
分治:LeetCode23、169、240
单调栈:LeetCode84、85、739、503
并查集:LeetCode547、200、684
滑动窗口:LeetCode209、3、1004、1208
前缀和:LeetCode724、560、437、1248
差分:LeetCode1094、121、122
拓扑排序:LeetCode210
字符串:LeetCode5、20、43、93
二分查找:LeetCode33、34
BFS:LeetCode127、139、130、529、815
DFS&回溯::LeetCode934、685、1102、531、533、113、332、337
动态规划:LeetCode213、123、62、63、361、1230
贪心算法:LeetCode55、435、621、452
字典树:LeetCode820、208、648
递归
70.爬楼梯
动态规划+滚动数组
f(n) = f(n-1) + f(n-2) dp
只与n,n-1,n-2有关 滚动数组,降低空间复杂度
class Solution {
public:
int climbStairs(int n) {
//动态规划+滚动数组
//f(n) = f(n-1) + f(n-2) dp
//只与n,n-1,n-2有关 滚动数组,降低空间复杂度
int dp[3] = {0};
//递归边界
dp[0] = 1;dp[1] = 1;dp[2] = 2; //dp[2]作为返回
if(n <= 2){
return dp[n];
}
for(int i = 3; i <= n; i++){
int temp = dp[2];
dp[2] += dp[1];
dp[1] = temp;
}
return dp[2];
}
};
112.路径总和
递归
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
//递归
if(root == nullptr) return false;
if(root->left == nullptr && root->right == nullptr){
return targetSum == root->val;
}
return hasPathSum(root->left,targetSum - root->val) || hasPathSum(root->right,targetSum - root->val);
}
};
509.斐波那契数
递归
class Solution {
public:
int fib(int n) {
if(n <= 1) return n;
return fib(n-1) + fib(n-2);
}
};
分治
23. 合并 K 个升序链表
分治合并
class Solution {
public:
//两两合并
ListNode* mergeTwoLists(ListNode *a,ListNode *b){
if((!a) || (!b)) return a?a:b; //两链表有胃口,则返回另一个非空的
//tail 指向合并的链表 aPtr,bPtr指向原先两个链表(指针形式),头节点head为空节点,不带数据
ListNode head,*tail = &head,*aPtr = a,*bPtr = b;
while(aPtr && bPtr){
if(aPtr->val < bPtr->val){
tail->next = aPtr;aPtr = aPtr->next;
} else {
tail->next = bPtr;bPtr = bPtr->next;
}
tail = tail->next;
}
tail->next = (aPtr ? aPtr : bPtr);
return head.next;
}
ListNode* merge(vector<ListNode*> &lists,int l,int r){
if(l == r) return lists[l]; //仅一个链表
if(l > r) return nullptr;
int mid = (l + r) >> 1;
return mergeTwoLists(merge(lists,l,mid),merge(lists,mid + 1,r));
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
return merge(lists,0,lists.size() - 1);
}
};
169. 多数元素
排序
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
return nums[nums.size()/2];
}
};
240. 搜索二维矩阵 II
二分查找
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
for(const auto& row : matrix){
auto it = lower_bound(row.begin(),row.end(),target);
if(it != row.end() && *it == target){
return true;
}
}
return false;
}
};
单调栈
符合后进先出,后进入案例先出结果
739. 每日温度
单调栈
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> ans(n);
stack<int> s; //单调栈
for(int i = 0; i < n; ++i){
while(!s.empty() && temperatures[i] > temperatures[s.top()]){
int pre = s.top();
ans[pre] = i - pre;
s.pop();
}
s.push(i);
}
return ans;
}
};