链式投票|流向贪心

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;

}

};

相关推荐
仰泳的熊猫13 小时前
题目2570:蓝桥杯2020年第十一届省赛真题-成绩分析
数据结构·c++·算法·蓝桥杯
无极低码16 小时前
ecGlypher新手安装分步指南(标准化流程)
人工智能·算法·自然语言处理·大模型·rag
软件算法开发16 小时前
基于海象优化算法的LSTM网络模型(WOA-LSTM)的一维时间序列预测matlab仿真
算法·matlab·lstm·一维时间序列预测·woa-lstm·海象优化
superior tigre17 小时前
22 括号生成
算法·深度优先
努力也学不会java18 小时前
【缓存算法】一篇文章带你彻底搞懂面试高频题LRU/LFU
java·数据结构·人工智能·算法·缓存·面试
旖-旎18 小时前
二分查找(x的平方根)(4)
c++·算法·二分查找·力扣·双指针
ECT-OS-JiuHuaShan19 小时前
朱梁万有递归元定理,重构《易经》
算法·重构
智者知已应修善业19 小时前
【51单片机独立按键控制数码管移动反向,2片74CH573/74CH273段和位,按键按下保持原状态】2023-3-25
经验分享·笔记·单片机·嵌入式硬件·算法·51单片机
khddvbe20 小时前
C++并发编程中的死锁避免
开发语言·c++·算法