力扣300:
第二题:
https://leetcode.cn/problems/spiral-matrix-iv/
用up,down,left,right 分别表示上下左右4个边界,当我们完成一行后,就压缩对应的边界。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
vector<vector<int>>res(m,vector<int>(n,-1));
ListNode*p=head;
int up=0,down=m-1;
int left=0,right=n-1;
int i=0;
while(p)
{
for(i=left;i<=right;++i)
{
res[up][i]=p->val;
p=p->next;
if(p==NULL) return res;
}
if(up<down) up++;
for(i=up;i<=down;++i)
{
res[i][right]=p->val;
p=p->next;
if(p==NULL) return res;
}
if(left<right) right--;
for(i=right;i>=left;--i)
{
res[down][i]=p->val;
p=p->next;
if(p==NULL) return res;
}
if(up<down) down--;
for(i=down;i>=up;--i)
{
res[i][left]=p->val;
p=p->next;
if(p==NULL) return res;
}
if(left<right) left++;
}
return res;
}
};
acw58:
第二题:
https://www.acwing.com/problem/content/4492/
首先,由题目可以知道a是递增的,选出满足a(i+1)<=ai×2的子序列。
可以对于a1到a(n−1)求出一个b数组,如果ai满足上面那个表达式,那么bi=bi=0。
最后求出b中连续1的个数中最大的值。
#include <bits/stdc++.h>
using namespace std;
const int N = 200010;
int n, a[N];
bool b[N];
int main() {
scanf("%d", &n);
for (int i = 1;i <= n; i++) scanf("%d", &a[i]);
for (int i = 1; i < n; i++)
if (a[i + 1] <= 2 * a[i]) b[i] = 1;
else b[i] = 0;
//标记是否可行
int res = 0, ans = 0;
for (int i = 1;i < n; i++) {
if (b[i] == 0) continue;
res = 1;
while (b[i + 1] == 1) res++, i++;
ans = max(ans, res);
}
printf("%d\n", ans + 1);
return 0;
}