链式投票|流向贪心

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;

}

};

相关推荐
UIU11410 小时前
P1115 最大子段和
c++·算法
垆边人似月.10 小时前
华为题:零钱兑换
算法·华为
Logic10110 小时前
C语言/数据结构组合数学题解:数字好排列计数——质数倍数分类与阶乘取模
c语言·数据结构·算法·组合数学·时间复杂度·排列·取模运算
碧海银沙音频科技研究院11 小时前
炬芯ATS3089智能手表烧录方法
人工智能·驱动开发·嵌入式硬件·算法
维克兜率天11 小时前
【维克】统计套利:寻找市场的“定价误差“
人工智能·python·算法
aqiu11111111 小时前
【C++算法打怪专栏】LeetCode 1. 两数之和(哈希表解法总结)
c++·算法·leetcode
楚识科技11 小时前
票据 OCR 识别技术深度解析:从算法原理到企业级落地实现
算法·ocr
longlongzihan11 小时前
LeetCode 25. K 个一组翻转链表 (迭代+分组反转法)
算法·leetcode·链表
xuxigifxfh11 小时前
牛客:BISHI8 大整数哈希
java·算法·哈希算法
涉密IT资质笔记11 小时前
涉密资质投入产出分析模型:时间成本、四块成本构成与 ROI 决策框架
java·开发语言·算法