链式投票|流向贪心

lc2147

抽离出座位位置,座位数非偶或为0则无方案,否则每两组座位间的间隔数相乘,取模得方案数。

class Solution {

typedef long long ll;

public:

int numberOfWays(string corridor)

{

int n=corridor.size();

vector<int> s;

for(int i=0;i<n;i++)

{

char c=corridor[i];

if(c=='S')

s.push_back(i);

}

int m=s.size();

if(m%2 || m==0) return 0;

ll ret=1;

const int mod=1e9+7;

for(int i=2;i<m;i+=2)

{

int d=s[i]-s[i-1];

ret=(ret*(ll)d)%mod;

}

return (int)(ret%mod);

}

};

lc2022

++if(len!=m*n)++

++return {};//check++

class Solution {

public:

vector<vector<int>> construct2DArray(vector<int>& original, int m, int n)

{

vector<vector<int>> ret(m,vector<int>(n,0));

int len=original.size();

++if(len!=m*n)++

++return {};//check++

for(int i=0;i<len;i++)

{

ret[i/n][i%n]=original[i];

}

return ret;

}

};

lc797

先凑总和非负,找唯一负数位置

从近到远取两边正数补负数,累计移动步数得最小操作数

class Solution {

public:

long long minMoves(vector<int>& balance) {

long long total = 0;

int neg_idx = -1;

for (int i = 0; i < balance.size(); i++) {

int x = balance[i];

total += x;

if (x < 0) {

neg_idx = i;

}

}

if (total < 0) { // 总和必须非负

return -1;

}

if (neg_idx < 0) { // 没有负数,无需操作

return 0;

}

int n = balance.size();

++int need = -balance[neg_idx];++

long long ans = 0;

++for (int dis = 1; ; dis++) {++

// 把与 neg_idx 相距 dis 的数移到 neg_idx

++int s = balance[(neg_idx - dis + n) % n] + balance[(neg_idx + dis) % n];++

if (s >= need) {

ans += 1LL * need * dis;

// need 个 1 移动 dis 次

return ans;

}

++ans += 1LL * s * dis; // s 个 1 移动 dis 次
need -= s;
++

}

}

};

lc277

1.找候选人

2.check候选人(3种situation)

/* The knows API is defined for you.

bool knows(int a, int b); */

class Solution

{

public:

int findCelebrity(int n)

{

int candidate = 0; //候选人

for (int x = 1; x < n; x ++)

{

if ( knows(candidate, x) == true ) //若候选人认识别人,就不可能是名人。名人不认识其他人

{

candidate = x; //所有人,一定认识名人

//////小于x的那些,要么是因为 (1)被人不知,if被人知,就抢到了candidate了

//////(2) 要么是因为认识了别人,就放弃了candidate

}

}

for (int x = 0 ; x < n; x ++)

{

if (candidate == x) //名人不认识其他人,但是认识自己

continue;

if ( knows(candidate, x) == true)

return -1; //名人不应该认识 anyone

if (knows(x, candidate) == false)

return -1; //anyone 认识名人

}

return candidate;

}

};

相关推荐
wuweijianlove1 小时前
算法性能的渐近与非渐近行为对比的技术4
算法
_dindong1 小时前
cf1091div2 C.Grid Covering(数论)
c++·算法
AI成长日志1 小时前
【Agentic RL】1.1 什么是Agentic RL:从传统RL到智能体学习
人工智能·学习·算法
黎阳之光2 小时前
黎阳之光:视频孪生领跑者,铸就中国数字科技全球竞争力
大数据·人工智能·算法·安全·数字孪生
skywalker_112 小时前
力扣hot100-3(最长连续序列),4(移动零)
数据结构·算法·leetcode
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 17. 电话号码的字母组合 | C++ 回溯算法经典模板
c++·算法·leetcode
wfbcg2 小时前
每日算法练习:LeetCode 209. 长度最小的子数组 ✅
算法·leetcode·职场和发展
_日拱一卒3 小时前
LeetCode:除了自身以外数组的乘积
数据结构·算法·leetcode
计算机安禾3 小时前
【数据结构与算法】第36篇:排序大总结:稳定性、时间复杂度与适用场景
c语言·数据结构·c++·算法·链表·线性回归·visual studio
SatVision炼金士3 小时前
合成孔径雷达干涉测量(InSAR)沉降监测算法体系
算法