计数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 nums0;

vector<bool> mask(n, false);

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

vector<pair<int, int>> arr;

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

arr.emplace_back(numsi, i);

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

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

for (auto& val, idx : arr)

{

if (!maskidx) { // 当前元素未标记

ret += val;

maskidx = true; // 标记自身

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

if (idx < n - 1) maskidx + 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)

prei = prei-1 + numsi-1;

int max_s = 0;

vector<int> res;

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

int l0 = i - prei;

++int r1 = pren - prei;++

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 (colorsi == colorsi-1)

count++;//相等_计数

else

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

if (colorsi-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 小时前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
To_OC5 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
Forever Nore8 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR8 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
Tisfy10 小时前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表
lucas_AI10 小时前
Q-CueGraph:你的多模态大模型会 zoom,但真的知道该看哪儿吗?
人工智能·算法
kaixin_啊啊11 小时前
test_机器学习算法学习
学习·算法·机器学习
liulilittle11 小时前
MOE路由:路由(logits: top-k/8)
c++·人工智能·算法·机器学习·llm
旖旎夜光11 小时前
LeetCode 11:盛最多水的容器(双指针问题) —— 题解
数据结构·c++·算法·leetcode·双指针