提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、螺旋矩阵II
题目描述:
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
代码如下(示例):
一维vector初始化:vectorans(size);//开size大小的vector
二维vector初始化的方法如下代码所示:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>>ret(n, vector<int>(n, 0));//给二维vector初始化n*n大小,且初值为0
int top=0;
int bottom=n;
int left=0;
int right=n;
int i=0,j=0;
int w=1;
while(left<right&&top<bottom){
if(i==top&&j==left){
while(j<right){
ret[i][j++]=w++;
}
top++;
i++;
}
else if(j==right&&i==top){
while(i<bottom){
ret[i++][j-1]=w++;
}
right--;
j--;
}
else if(j==right&&i==bottom){
while(j>left){
ret[i-1][--j]=w++;
}
bottom--;
i--;
}
else if(j==left&&i==bottom){
while(i>top){
ret[--i][j]=w++;
}
left++;
j++;
}
}
return ret;
}
};
二.旋转链表
题目描述:
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
思路:由于链表的长度未知,所以当head->next!=nullptr时,需要用到两个指针来定位末节点
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(head==nullptr){
return nullptr;
}
if(head->next==nullptr||k==0){
return head;
}
//当k>1时,需要借助前后指针来定位最后一个节点
ListNode *pre=head;
ListNode *back=head;
int l=0;
int flag=0;
for(int i=0;i<k;i++){
l++;
if(pre->next==nullptr){
pre=head;
flag=1;
break;
}
pre=pre->next;
}
if(flag){
k=k%l;
for(int i=0;i<k;i++){
pre=pre->next;
}
}
if(pre==head){
return head;
}
while(pre->next!=nullptr){
pre=pre->next;
back=back->next;
}
ListNode *ret=back->next;
back->next=nullptr;
pre->next=head;
return ret;
}
};
三.贪心算法求最大利润
题目描述:
假设 力扣(LeetCode)即将开始 IPO 。为了以更高的价格将股票卖给风险投资公司,力扣 希望在 IPO 之前开展一些项目以增加其资本。 由于资源有限,它只能在 IPO 之前完成最多 k 个不同的项目。帮助 力扣 设计完成最多 k 个不同项目后得到最大总资本的方式。
给你 n 个项目。对于每个项目 i ,它都有一个纯利润 profits[i] ,和启动该项目需要的最小资本 capital[i] 。
最初,你的资本为 w 。当你完成一个项目时,你将获得纯利润,且利润将被添加到你的总资本中。
总而言之,从给定项目中选择 最多 k 个不同项目的列表,以 最大化最终资本 ,并输出最终可获得的最多资本。
答案保证在 32 位有符号整数范围内。
输入:k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]
输出:4
解释:
由于你的初始资本为 0,你仅可以从 0 号项目开始。
在完成后,你将获得 1 的利润,你的总资本将变为 1。
此时你可以选择开始 1 号或 2 号项目。
由于你最多可以选择两个项目,所以你需要完成 2 号项目以获得最大的资本。
因此,输出最后最大化的资本,为 0 + 1 + 3 = 4。
/*
将利润和资本按顺序排列好,将所有符合资本小于等于w的利润添加至大根堆中,
每次获取最大利润并更新w值,直至大根堆中无元素或k<=0。
*/
class Solution {
public:
int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) {
vector<pair<int,int>>temp;
int n=profits.size();
for(int i=0;i<n;i++){
temp.push_back({capital[i],profits[i]});
}
sort(temp.begin(),temp.end());
priority_queue<int,vector<int>,less<int>>pq;//大根堆
int curr=0;
for(int i=0;i<n;i++){
while(curr<n&&temp[curr].first<=w){
pq.push(temp[curr].second);
curr++;
}
if(k>0&&!pq.empty()){
k--;
w+=pq.top();
pq.pop();
}
else{
break;
}
}
return w;
}
};