当前位置:网站首页>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 情侣牵手
边栏推荐
猜你喜欢
Vscode连接远程服务器(一套配置成功)
如何根据地址获取函数名
功耗控制之DVFS介绍
MySQL基础篇【子查询】
[Cultivation of internal skills of string functions] strlen + strstr + strtok + strerror (3)
3. Actual combat---crawl the result page corresponding to Baidu's specified entry (a simple page collector)
一点点读懂cpufreq(二)
一点点读懂cpufreq(一)
一、爬虫基本概念
【七夕快乐篇】Nacos是如何实现服务注册功能的?
随机推荐
当panic或者die被执行时,或者发生未定义指令时,如何被回调到
对写作的一些感悟
OpenCV:10特征检测
Since a new byte of 20K came out, I have seen what the ceiling is
MongoDB permission verification is turned on and mongoose database configuration
Chinese and Japanese color style
golang 协程的实现原理
安全软件 Avast 与赛门铁克诺顿 NortonLifeLock 合并案获英国批准,市值暴涨 43%
uniapp sharing function - share to friends group chat circle of friends effect (sorting)
[QNX Hypervisor 2.2用户手册]10.4 vdev hpet
一点点读懂regulator(三)
@Import注解的作用以及如何使用
C语言实现扫雷 附带源代码
Xiaohei leetcode surfing: 94. Inorder traversal of binary tree
~ hand AHB - APB Bridge 】 【 AMBA AHB bus
七牛云图片上传
[Cultivation of internal skills of string functions] strncpy + strncat + strncmp (2)
MySQL的安装与卸载
生产者消费者问题
4-《PyTorch深度学习实践》-反向传播