当前位置:网站首页>换座位[异或巧妙的让奇偶互换]
换座位[异或巧妙的让奇偶互换]
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 换座位
边栏推荐
猜你喜欢
提升用户体验,给你的模态弹窗加个小细节
供应商对接Chewy的EDI需求
etcd Study Notes - Getting Started
gopacket usage example
杰理之采用mix out eq 没有作用【篇】
JVM垃圾回收机制简介
容易混淆的指针知识点
2022年安全员-A证特种作业证考试题库及在线模拟考试
[Server data recovery] A case of data recovery when the Ext4 file system cannot be mounted and an error is reported after fsck
HP路由器和交换机日志分析
随机推荐
Base64编码和图片转化
数量遗传学遗传力计算2:半同胞和全同胞
FFmpeg编译支持x264/openH264/dash
全栈代码测试覆盖率及用例发现系统的建设和实践
【暑期每日一题】洛谷 P1200 [USACO1.1]你的飞碟在这儿Your Ride Is Here
HP路由器和交换机日志分析
761. 特殊的二进制序列(分治)
360 评估反馈问题的示范案例
杰理之开关降噪语音识别没有用【篇】
【数学建模绘图系列教程】绘图模板总结
特征工程实战篇
Query the size of the total points obtained in a certain time period to sort
ceph创建存储池,映射,删除练习
2022年安全员-B证考试练习题及在线模拟考试
【服务器数据恢复】Ext4文件系统fsck后mount不上并报错的数据修复案例
I.MX6U-ALPHA开发板(高精度定时器)
使用ceph-deploycep集群部署,并用3个磁盘作为专用osd
Construction and practice of full stack code test coverage and use case discovery system
2022 High-altitude installation, maintenance, and demolition exam practice questions and mock exams
基于ABP和Magicodes实现Excel导出操作