21. 栈的压入、弹出序列
栈的压入、弹出序列_牛客题霸_牛客网 (nowcoder.com)
既然是栈的序列,那就用栈模拟。
class Solution {
public:
bool IsPopOrder(vector<int>& pushV, vector<int>& popV) {
if(pushV.empty() || popV.empty()) return false;
stack<int> st;
int j = 0;
for(int i = 0;i<pushV.size();i++){
st.push(pushV[i]);
while(!st.empty() && st.top() == popV[j]){
j++;
st.pop();
}
}
return st.empty();
}
};
22. 从上往下打印二叉树
从上往下打印二叉树_牛客题霸_牛客网 (nowcoder.com)
我一个层序遍历就出来了。
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
queue<TreeNode*> que;
vector<int> ans;
if(root != nullptr) que.push(root);
while(!que.empty()){
int size = que.size();
for(int i = 0;i<size;i++){
TreeNode* node = que.front();
que.pop();
ans.push_back(node->val);
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return ans;
}
};
23. 二叉搜索树的后序遍历序列
二叉搜索树的后序遍历序列_牛客题霸_牛客网 (nowcoder.com)
法一:递归
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if(sequence.empty()) return false;
return check(sequence,0,sequence.size() - 1);
}
bool check(vector<int>& sequence,int l, int r){
if(l >= r) return true;
int root = sequence[r];
int j = r - 1;
while(j >= 0 && sequence[j] > root) j--;
for(int i = 0;i<j;i++){
if(sequence[i] > root) return false;
}
return check(sequence,l,j) && check(sequence, j + 1, r - 1);
}
};
法二:
- 二叉树的中序遍历和后序遍历对应着一种栈的压入、弹出序列。
- 若是二叉搜索树,对后序遍历序列排序就得到了中序遍历序列。
- 将中序遍历序列作为入栈序列,检查后续遍历序列是否是一个合法的出栈序列即可(栈的压入、弹出)
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if(sequence.empty()) return false;
vector<int> inorder(sequence);
sort(inorder.begin(),inorder.end());
return isPopOrder(inorder,sequence);
}
bool isPopOrder(vector<int> pushV,vector<int>& popV){
if(pushV.empty() || popV.empty()) return false;
stack<int> st;
int j = 0;
for(int i = 0;i<pushV.size();i++){
st.push(pushV[i]);
while(!st.empty()&& st.top() == popV[j]){
j++;
st.pop();
}
}
return st.empty();
}
};
24. 二叉树中和为某一值的路径
二叉树中和为某一值的路径(二)_牛客题霸_牛客网 (nowcoder.com)
回溯法,也是DFS。
class Solution {
public:
vector<vector<int>> ans;
vector<int> path;
void bt(TreeNode* root,int sum){
if(root == nullptr) return ;
path.push_back(root->val);
sum -= root->val;
if(root->left == nullptr && root->right == nullptr && sum == 0)
ans.push_back(path);
bt(root->left,sum);
bt(root->right,sum);
path.pop_back();
}
vector<vector<int> > FindPath(TreeNode* root, int target) {
// write code here
bt(root,target);
return ans;
}
};
25. 复杂链表的复制
复杂链表的复制_牛客题霸_牛客网 (nowcoder.com)
法一:
将整个复杂过程分为三部。
- 在每个节点后面插入对应的拷贝节点。
- 遍历一次连表,逐个复制每个原有节点的random指针内容到拷贝节点中。(使用双指针,一个指向原链表的节点,一个指向拷贝链表的节点)
- 用双指针将链表拆分。
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead) {
if(!pHead) return nullptr;
RandomListNode* cur = pHead;
// 每个节点后面新增对应拷贝节点
while(cur){
RandomListNode* temp = new RandomListNode(cur->label);
temp->next = cur->next;
cur->next = temp;
cur = temp->next;
}
RandomListNode *old = pHead,*clone = pHead->next,*ret = pHead->next;
// 拷贝random指针内容
while(old){
clone->random = old->random == nullptr ? nullptr : old->random->next;
if(old->next) old = old->next->next;
if(clone->next) clone = clone->next->next;
}
// 将链表拆分
old = pHead,clone = pHead->next;
while(old){
if(old->next) old->next = old->next->next;
if(clone->next) clone->next = clone->next->next;
old = old->next;
clone = clone->next;
}
return ret;
}
};
法二
本题的复杂之处在于多了一个random指针的复制。next指针的复制十分轻松,但复制之后如何完成random指针的复制是个问题。可以考虑在复制next指针时,用哈希表存储原节点与复制节点的映射。这样只要两次遍历,第一次复制next指针,第二次根据映射关系将原来random的指向映射到新链表上即可完成random指针的复制。
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead) {
if(!pHead) return pHead;
RandomListNode* dummy = new RandomListNode(0);
RandomListNode* cur = pHead;
RandomListNode* pre = dummy;
unordered_map<RandomListNode*, RandomListNode*> mp;
while(cur){
RandomListNode* temp = new RandomListNode(cur->label);
pre->next = temp;
mp[cur] = temp;
cur = cur->next;
pre = pre->next;
}
for(auto& [key,value] : mp){
value->random = key->random == nullptr ? nullptr : mp[key->random];
}
return dummy->next;
}
};
26. 二叉搜索树与双向链表
二叉搜索树与双向链表_牛客题霸_牛客网 (nowcoder.com)
法一:
先中序遍历二叉树,将其放入一个vector中,然后遍历vector改变指针朝向即可。但这样做在push_back时也属于创建了新的节点,而不是直接改变指针朝向。
class Solution {
public:
vector<TreeNode*> vec;
void inorder(TreeNode* root){
if(!root) return ;
inorder(root->left);
vec.push_back(root);
inorder(root->right);
}
TreeNode* Convert(TreeNode* pRootOfTree) {
if(!pRootOfTree) return nullptr;
inorder(pRootOfTree);
for(int i = 0;i<vec.size() - 1;i++){
vec[i]->right = vec[i + 1];
vec[i+1]->left = vec[i];
}
return vec[0];
}
};
法二:
用一个全局的pre指针记录当前遍历节点的前继节点。
每次递归处理过程中,root->left = pre。并且pre->right = root
。最后pre = root
,更新pre
的值。
class Solution {
public:
TreeNode* pre = nullptr;
TreeNode* Convert(TreeNode* pRootOfTree) {
if(!pRootOfTree) return nullptr;
TreeNode* ans = pRootOfTree;
while(ans->left) ans = ans->left;
inorder(pRootOfTree);
return ans;
}
void inorder(TreeNode* root){
if(!root) return ;
inorder(root->left);
root->left = pre;
if(pre){
pre->right = root;
}
pre = root;
inorder(root->right);
}
};
27. 字符串的排列
字符串的排列_牛客题霸_牛客网 (nowcoder.com)
法一:
用回溯法,相当于求有重复元素数组的全排列。
- 由于有重复元素,故需要去重
- 由于求全排列需要用回溯。
- 递归三部曲:
- 递归参数:由于求全排列,故需要用一个数组记录已经访问过的元素,下次递归过来就不访问了。
- 递归终止条件:当
path.size() == str.size()
表示str已经遍历完了,就终止。 - 单层搜索的逻辑:每次都需要从0开始遍历整个str。中间遇到已经访问过的元素,则
continue
。
- 去重:由于str中存在重复元素,需要去重。例如”aa”,若不去重,会有
[a,a]
、[a,a]
两种结果。- 去重首先需要将str中各个元素排序。
- 之后在递归的树形结构中,used记录了是否访问过,str记录了所有数据。如果
str[i] == str[i-1]
表明需要考虑去重。 - 若此时,
used[i-1] = false
表明该在本次全排列计算过程中used[i-1]没有访问过,此时如果继续递归会重复。举例如下:对于[1,1,2]
,在以第二个1为首元素时,used[i-1]= false
。此时如果继续递归下去,和以第一个1为首元素进行递归的结果会重复。 - 若此时,
used[i-1] = true
表明在本次全排列计算时,used[i-1]已经访问过,此时不应去重。举例如下:对于[1,1,2]
,表明第一个元素为1,第二个元素为1的情况,此时应该继续递归去寻找第三个元素。如果此时直接跳过,得到的全排列中的各个元素之间都是不重复的,这就与题意不符了。
class Solution {
public:
vector<string> ans;
string path;
void bt(string& str,vector<bool>& used){
if(path.size() == str.size()){
ans.push_back(path);
return ;
}
for(int i = 0;i<str.size();i++){
if(i >0 && str[i] == str[i - 1] && used[i - 1] == false) continue;
if(used[i] == true) continue;
used[i] = true;
path.push_back(str[i]);
bt(str,used);
path.pop_back();
used[i] = false;
}
}
vector<string> Permutation(string str) {
sort(str.begin(),str.end());
vector<bool> used(str.size(),false);
bt(str,used);
return ans;
}
};
法二:
使用STL 中的**next_permutation
**返回全排列。该函数必须先排序才能使用。
class Solution {
public:
vector<string> Permutation(string str) {
vector<string> ans;
sort(str.begin(),str.end());
do{
ans.push_back(str);
}while(next_permutation(str.begin(), str.end()));
return ans;
}
};
28. 数组中出现次数超过一半的数字
数组中出现次数超过一半的数字_牛客题霸_牛客网 (nowcoder.com)
法一:
排序后直接返回中间位置的数即可。
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int>& numbers) {
sort(numbers.begin(),numbers.end());
return numbers[numbers.size() / 2];
}
};
法二:
用哈希表记录一下每个元素有几个。
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int>& numbers) {
unordered_map<int,int> mp;
for(auto& i : numbers){
mp[i]++;
if(mp[i] > numbers.size() / 2) return i;
}
return -1;
}
};
法三:
摩尔投票法:寻找一组元素中占多数的元素的算法。时间复杂度O(n)。
- 基本思想:每次从序列中选两个不相同的数字删除掉(“抵消”),最后剩下一个数字或几个相同的数字,就是出现次数大于总数一般的那个。
- 实现:
- 设置一个计数器遍历时遇到不同数字就-1,遇到相同数字就+1。
- 只要在计数器归0时,就重新假定当前数字为众数继续遍历。
- 最后,计数器记录的数字就可能是众数。
- 最后再遍历一次数组,看看该数出现了几次,或者直接用STL中的count()数一下就好。
- 由于本题确定众数存在,故找到可能的众数后返回即可。
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int>& numbers) {
int cnt = 0,num = 0;
for(int i = 0;i<numbers.size();i++){
if(cnt == 0){
num = numbers[i];
cnt = 1;
}else{
numbers[i] == num ? cnt++ : cnt--;
}
}
return num;
}
};
29. 最小的K个数
最小的K个数_牛客题霸_牛客网 (nowcoder.com)
法一
排序之后慢慢数。
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int>& input, int k) {
sort(input.begin(),input.end());
vector<int> ans;
for(int i = 0;i<k;i++){
ans.push_back(input[i]);
}
return ans;
}
};
法二
用优先队列(小根堆)。
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int>& input, int k) {
// priority_queue默认为大根堆,故需要用第三个参数指明是小根堆
priority_queue<int,vector<int>,greater<int>> pq;
for(auto& i : input) pq.push(i);
vector<int> ans;
while(k--){
ans.push_back(pq.top());
pq.pop();
}
return ans;
}
};
补充:C++中优先队列的用法。
- 定义:
priority_queue<Type, Container, Functional>
- Type:数据类型
- Container:容器类型,必须是连续存储空间容器,比如vector,deque等,STL默认用vector。
- Functional:比较的方式。使用自定义数据类型时需要用该参数表示如何比较类型的大小。使用基本数据类型时,只需要传入数据类型,默认大顶堆。
//升序队列(小顶堆)
priority_queue <int,vector<int>,greater<int> > pq;
//降序队列(大顶堆)
priority_queue <int,vector<int>,less<int> > pq;
- greater和less是两个仿函数(使一个类的使用看起来像个函数,就是类中实现了一个
operator()
)。
30. 连续子数组的最大和
连续子数组的最大和_牛客题霸_牛客网 (nowcoder.com)
法一
常规dp。dp[i]
表示以array[i]
结尾的连续子数组的最大和。
class Solution {
public:
int FindGreatestSumOfSubArray(vector<int>& array) {
vector<int> dp(array.size(),0);
dp[0] = array[0];
int ans = array[0];
for(int i = 1;i<array.size();i++){
dp[i] = max(array[i],dp[i-1] + array[i]) ;
ans = max(ans,dp[i]);
}
return ans;
}
};
法二
利用array的空间作为dp数组,减少空间复杂度。
class Solution {
public:
int FindGreatestSumOfSubArray(vector<int>& array) {
int ans = array[0];
for(int i = 1;i<array.size();i++){
array[i] = max(0,array[i-1]) + array[i];
ans = max(ans,array[i]);
}
return ans;
}
};
法三
贪心算法。
- 连续子数组的最大值的贪心原则是在累加过程中只要中间结果≥0就不中断计数。
- 例如,
4,-1,2
中虽然4
与-1
的和比4
小,但其还是正数与之后的2
相加时还会贡献一部分数值。 - 这样做的一个问题是,连续子数组的最大值可能在中间结果产生,例如
4,-2,1
中最大结果为4,而如果用一个变量来进行累加,该变量的值最后是3
。 - 该问题的解决方案是用一个变量专门记录最大值,在每次累加过程后都更新以下该变量。
具体实现而言,可以用一个计数器cnt
记录寻找过程中的子数组和。
在累加的过程中,遵循以下规则。
- 当遇到正数或零时,我们直接将其加到计数器
cnt
上,并同时更新记录的最大值。 - 若遇到负数,需要考虑两种状态
- 如果将负数加到当前的累加结果后仍然得到正数,比如
3 + (-2)
。此时则将负数加到累加结果上,并继续累加。这是因为这样做有可能对后续的连续子数组结果产生增益。 - 如果将负数加到当前的累加结果后变成了负数,比如
1 + (-2)
。此时,将负数加到当前结果会对之后的连续子数组结果产生负面影响。故将cnt
清零,重新开始累加。
- 如果将负数加到当前的累加结果后仍然得到正数,比如
class Solution {
public:
int FindGreatestSumOfSubArray(vector<int>& array) {
int ans = INT_MIN;
int cnt = 0;
for(int i = 0;i<array.size();i++){
cnt += array[i];
ans = max(ans,cnt);
if(cnt < 0) cnt = 0;
}
return ans;
}
};