链式投票|流向贪心

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=corridori;

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=si-si-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++)

{

reti/ni%n=originali;

}

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 = balancei;

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 = -balanceneg_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;

}

};

相关推荐
lsylalalala1 小时前
常见的排序算法1
数据结构·算法·排序算法
想吃火锅10052 小时前
【leetcode】54. 螺旋矩阵
算法·leetcode·矩阵
想吃火锅10052 小时前
【leetcode】300. 最长递增子序列
算法·leetcode·职场和发展
imaol13 小时前
数据结构---队列
java·数据结构·算法
数模竞赛Paid answer3 小时前
2026年电工杯数学建模A题绿电直连型电氢氨园区优化运行求解全过程论文及程序
算法·数学建模·电工杯
疯狂打码的少年3 小时前
【数据结构】串的模式匹配:KMP算法(重点)
数据结构·笔记·算法
晚风醉蝶4 小时前
第零篇-算法全景图
算法
疯狂打码的少年4 小时前
【数据结构】树的基本概念与二叉树定义
java·数据结构·笔记·算法
webmote334 小时前
用 NVIDIA Nemotron 3 Super + .NET 构建有记忆的多轮对话
后端·算法
Keven_114 小时前
算法札记:区分稀疏图与稠密图在经验上的数学计算差异
算法·稠密图·稀疏图