当前位置:网站首页>Couple Holding Hands [Greedy & Abstract]
Couple Holding Hands [Greedy & Abstract]
2022-08-04 23:48:00 【REN_Linsen】
前言
Greed is a good question to examine analytical skills,Especially the ones that are intrusive,That is, we need to extract useful information,去伪存真,The problem can be abstracted away.动态规划也是一样,If there is no abstract thinking to extract vital information,The state cannot be defined,Naturally, there is no way to find out how to transfer the state.Of course reading comprehension questions/脑筋急转弯,This ability to abstract useful information is even more needed.
一、情侣牵手
二、贪心&抽象
package everyday.hard;
// 情侣牵手.
public class MinSwapsCouples {
/* 抽象思维:其实我们并不关心1/2/3...这些位置,We only care about special adjacencies<0,1><2,3>. Then a pair of special positions<x,y>,有2种情况.First, couples don't care;The second is not a couple,can be replaced1个人,Can also be replaced2个人. Since we only care about adjacent positions,That is to replace the boys of the two couples,换个角度看,In fact, it can also be seen as replacing the two girls,So what we care about is the adjacent pair,rather than a special location. 所以,根据贪心,换1The way of man is the best,leave alone,Just replace it less often. */
public int minSwapsCouples(int[] row) {
int cnt = 0;
for (int i = 0; i < row.length; i += 2) {
int target = (row[i] & 1) == 0 ? row[i] + 1 : row[i] - 1;
if (target == row[i + 1]) continue;
findAndSwap(row, i + 1, target);
cnt++;
}
return cnt;
}
private void findAndSwap(int[] row, int begin, int target) {
int i = begin + 1;
while (i < row.length && target != row[i]) ++i;
row[i] = row[begin];
row[begin] = target;
}
}
总结
1)Practice greed problems more,Exercise analytical skills & Information processing ability & Information extraction and transformation capabilities.
参考文献
[1] LeetCode 情侣牵手
边栏推荐
猜你喜欢
Go 语言快速入门指南:什么是 TSL 安全传输层
First, the basic concept of reptiles
NebulaGraph v3.2.0 Release Note,对查询最短路径的性能等多处优化
MySQL基础篇【聚合函数】
MySQL基础篇【子查询】
Develop a SpaceX website based on the Appian low-code platform
【七夕情人节特效】-- canvas实现满屏爱心
2022牛客暑期多校训练营5(BCDFGHK)
4 - "PyTorch Deep Learning Practice" - Backpropagation
建模师经验分享:模型学习方法
随机推荐
测试技术:关于上下文驱动测试的总结
如何写好测试用例
3年,从3K涨薪到20k?真是麻雀啄了牛屁股 — 雀食牛逼呀
LeetCode Hot 100
情人节---快来学习一下程序员的专属浪漫吧
uniapp 分享功能-分享给朋友群聊朋友圈效果(整理)
未上市就“一举成名”,空间媲美途昂,安全、舒适一个不落
KT148A语音芯片ic工作原理以及芯片的内部架构描述
npm基本操作及命令详解
一点点读懂thermal(一)
truffle
what is MVCC
4-《PyTorch深度学习实践》-反向传播
线程三连鞭之“线程的状态”
MySQL增删改查基础
小黑leetcode之旅:95. 至少有 K 个重复字符的最长子串
安全软件 Avast 与赛门铁克诺顿 NortonLifeLock 合并案获英国批准,市值暴涨 43%
Chinese and Japanese color style
加解密在线工具和进制转化在线工具
C语言实现扫雷 附带源代码