计数if|

lc2593

1.mask ll也会溢出 转vec bool

2.sort pii(nums,idx) 后标记自身 &左右

一次遍历即可

class Solution {

typedef long long ll;

public:

long long findScore(vector<int>& nums) {

ll ret = 0;

int n = nums.size();

if (n == 1) return nums[0];

vector<bool> mask(n, false);

// 1. 元素按"值+下标"排序

vector<pair<int, int>> arr;

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

arr.emplace_back(nums[i], i);

sort(arr.begin(), arr.end());

// 2. 按排序处理,用mask标记

for (auto& [val, idx] : arr)

{

if (!mask[idx]) { // 当前元素未标记

ret += val;

mask[idx] = true; // 标记自身

if (idx > 0) mask[idx - 1] = true; // 标记左邻

if (idx < n - 1) mask[idx + 1] = true; // 标记右邻

}

}

return ret;

}

};

lc2155

presum预处理

class Solution {

public:

vector<int> maxScoreIndices(vector<int>& nums)

{

int n = nums.size();

vector<int> pre(n + 1);

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

pre[i] = pre[i-1] + nums[i-1];

int max_s = 0;

vector<int> res;

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

int l0 = i - pre[i];

++int r1 = pre[n] - pre[i];++

int s = l0 + r1;

if (s > max_s) {

max_s = s;

res = {i};

}

else if (s == max_s)

res.push_back(i);

}

return res;

}

};

lc2216

模拟栈

维护一个有效序列,遇到"偶数长度序列末尾元素和当前元素相同"的情况就替换末尾元素,最后保证序列是偶数长度

++原数组长度减去有效长度得到最少删除次数++

class Solution {

public:

int minDeletion(vector<int>& nums) {

vector<int> ans;

for (int num : nums) {

if (ans.size() > 0 && ++num == ans.back() && ans.size() % 2 == 1)++

continue;//ignore

else

ans.push_back(num);

}

int len = ans.size() % 2 == 0 ? ans.size() : ans.size() - 1;

++return nums.size() - len;++

}

};

lc2038

统计连续相同颜色的长度

class Solution {

public:

bool winnerOfGame(string colors)

{

int n = colors.size();

if (n < 3) return false;

int alice = 0, bob = 0;

int count = 1;

// 记录当前连续相同字符的长度

for (int i = 1; i < n; ++i) {

if (colors[i] == colors[i-1])

count++;//相等_计数

else

{ // 不等_统计上一段连续字符的可op

if (colors[i-1] == 'A')

alice += max(0, count - 2);

else

bob += max(0, count - 2);

++count = 1;//重置++

}

}

++// 处理最后一段连续字符
if (colors.back() == 'A')
++

alice += max(0, count - 2);

else

bob += max(0, count - 2);

return alice > bob;

}

};

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