当前位置:网站首页>换座位[异或巧妙的让奇偶互换]
换座位[异或巧妙的让奇偶互换]
2022-08-09 04:41:00 【REN_林森】
前言
将奇数id和偶数id的其他字段交换,同时考察转换问题能力 & 直接分析能力。如 换其他字段 和 换id是镜像对称的,换了其他字段就等同于换了id。
一、换座位
二、直接法 & 转换法 + 巧妙异或
1、直接法
# 直接法,联表。
with view4base as(
select s1.id,s1.student,s2.student next
from Seat s1 left join Seat s2 on s1.id & 1 = 1 and s1.id + 1 = s2.id or s1.id & 1 = 0 and s1.id - 1 = s2.id
)
select
id,
if(next is null,student,next) student
from view4base
# 直接法,联表改进。
with view4base as(
select s1.id,s1.student,s2.student next
from Seat s1 left join Seat s2 on (s1.id + 1) ^ 1 - 1 = s2.id # 让奇数先加一再加一,让偶数先加一再减一 一直不变,两者减一即可。
)
select
id,
if(next is null,student,next) student
from view4base
2、转换法
# 问题转换法,把它们id换了再排序。
select
case
when total & 1 = 1 and id = total then id
when id & 1 = 1 then id + 1
when true then id - 1
end id,
student
from Seat,(select max(id) total from Seat) t # 巧用笛卡儿积,而不是窗口函数。
order by id
# 问题转换法,巧妙的奇偶交换。
select
if(total & 1 = 1 and total = id,id,(id + 1) ^ 1 - 1) id,
student
from Seat,(select max(id) total from Seat) t # 巧用笛卡儿积,而不是窗口函数。
order by id
总结
1)巧妙的异或位运算,让奇偶数互换。
2)多锻炼问题转换的能力,如换id 和 换其他字段,是镜像对称的,换了id不就等同于换了其他大把字段,像是四两拨千斤的感觉。又比如筛选记录时,筛选了外键即另一张表的主键,就筛选除了特定信息,不一定要联表来做。
参考文献
[1] LeetCode 换座位
边栏推荐
- 【二叉树】重建二叉树
- 特征工程实战篇
- 2022 Security Officer-A Certificate Special Work Permit Exam Question Bank and Online Mock Exam
- 杰理之播歌曲前后音量大小不一样【篇】
- Construction and practice of full stack code test coverage and use case discovery system
- MySQL: Implementation Principles of Submitted Read and Repeatable Read | MVCC (Multi-Version Concurrency Control) - Notes for Your Own Use
- 整数倍数数列
- Gopacket source code analysis
- JS-全局dom对象的使用---使用htm样式和js函数动作的完全分离
- 助力To B业务,这类企业端数据值得风控童鞋关注
猜你喜欢
JS-DOM-对象的事件onload、匿名函数、this
安装pytorch和cuda
Ali YunTianChi competition problem (machine learning) - O2O coupons prediction (complete code)
MySQL: Intent Shared Locks and Intentional Exclusive Locks | Deadlocks | Lock Optimization
串扰与防护
Talking about the process and how to create it
How to do the stability test, this article thoroughly explains it!
供应商对接Chewy的EDI需求
阿里云天池大赛赛题(机器学习)——天猫用户重复购买预测(完整代码)
2分钟,带你走完企业经营分析全流程,更有通用分析框架直接套用
随机推荐
ABP中的数据过滤器
「竞品分析报告」不会写?不知从哪收集数据?请收下这篇竞品指南
[math] dot product and cross product
浅谈进程与其创建方式
2022年安全员-A证特种作业证考试题库及在线模拟考试
Correct use of BaseDexClassLoader
FFmpeg编译支持x264/openH264/dash
阿里云天池大赛赛题(机器学习)——阿里云安全恶意程序检测(完整代码)
Introduction to JVM garbage collection mechanism
Crosstalk and Protection
『HarmonyOS』Page与AbilitySlice的生命周期
Oracle 的开窗函数使用详解
全栈代码测试覆盖率及用例发现系统的建设和实践
etcd Study Notes - Getting Started
MySQL:意向共享锁和意向排它锁 | 死锁 | 锁的优化
360 评估反馈问题的示范案例
杰理之手机OTG问题【篇】
特征工程实战篇
ceph create pool, map, delete exercises
2022R1快开门式压力容器操作考试模拟100题及在线模拟考试