【BAOJ2456】【mode】【坑题】

本文介绍了一种在有限空间内查找数列中众数的算法。通过扫一遍数列,利用不同数相撞消失的原理,最终剩余的数即为众数。此算法适用于大规模数据集且内存资源有限的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

给你一个n个数的数列,其中某个数出现了超过n div 2次即众数,请你找出那个数。

Input

第1行一个正整数n。
第2行n个正整数用空格隔开。

Output

    一行一个正整数表示那个众数。

Sample Input

5
3 2 3 1 3

Sample Output

3

HINT

100%的数据,n<=500000,数列中每个数<=maxlongint。

题解:因为空间只有1M所以随机化,离散化什么的直接不用考虑。因为这个数出现超过n/2次,所以如果这个数和其他数两两相消的话最后剩下的一定是这个数。所以我们扫一遍,让不一样的数相撞消失就好了。

#include<cstdio>
using namespace std;
int now,temp,a,n;
int main()
{
    scanf("%d",&n);
    while (n--)
    {
        scanf("%d",&a);
        if (now==a) temp++;
        else temp--;
        if (temp<=0) {temp=1;now=a;}
    }
    printf("%d",now);
} 


from PyQt6.QtCore import QTimer from PyQt6.QtGui import QPixmap from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QProgressBar, QCheckBox from S08dome import Ui_Form from S08mode2 import Ui_Form1 from serial_son import SerialThread from arcade import load_sound, play_sound, stop_sound import serial.tools.list_ports import warnings import re class sonwindow(QWidget,Ui_Form1): def __init__(self): super().__init__() self.setupUi(self) class MyWindow(QWidget, Ui_Form): def __init__(self): super().__init__() self.setupUi(self) self.setWindowTitle("Serial Com") self.serial_thread = None self.open_serial_flag = False self.zdon = False self.pushButton_7.clicked.connect(self.mode) self.pushButton_8.clicked.connect(self.baoj) self.pushButton_11.clicked.connect(self.zp) self.pushButton_12.clicked.connect(self.nobaoj) self.horizontalSlider_4.valueChanged.connect(self.up) self.spinBox_3.valueChanged.connect(self.dowm) self.horizontalSlider_3.valueChanged.connect(self.up2) self.spinBox_4.valueChanged.connect(self.dowm2) self.pushButton_2.clicked.connect(self.open_serial_modbus) self.pushButton_6.clicked.connect(self.sx_ck) self.pushButton_4.clicked.connect(self.send_custom_instruction_with_delay) # self.checkBox.clicked.connect()# 设置初值 # self.comboBox_2.setValue(1) # 设置初值 self.pushButton_3.clicked.connect(self.son) # self.son = sonwindow() self.timer = QTimer(self) #######进度条 self.jdt_cz = 0 self.flat = 1 self.run = False self.progressBar_2.setValue(self.jdt_cz) self.progressBar_2.setRange(0,100) self.pushButton_9.clicked.connect(self.fx_flag) self.timer = QTimer(self) self.timer.timeout.connect(self.update) def fx_flag(self): if self.openmen == False: if not self.run: # 如果定时器未运行,启动并设置方向 self.run = True self.timer.start(50) # 间隔50ms else: # 如果定时器在运行,切换方向 self.flat *= -1 def update(self): self.jdt_cz += self.flat # 边界保护 if self.openmen == False: if self.jdt_cz >= 100: self.jdt_cz = 100 self.timer.stop() self.run = False self.flat = -1 # 下自动反向 self.lineEdit_6.setText("打开") self.pp = False elif self.jdt_cz <= 0: self.jdt_cz = 0 self.timer.stop() self.run = False self.flat = 1 # 下自动反向 self.lineEdit_6.setText("关闭") self.pp = True self.progressBar_2.setValue(self.jdt_cz) ###子页面 def son(self): self.son_1 = sonwindow() self.son_1.show() ###滑条 def up(self,num): self.horizontalSlider_4.setValue(num) self.spinBox_3.setValue(num) def dowm(self,num): self.horizontalSlider_4.setValue(num) self.spinBox_3.setValue(num) def up2(self,num2): self.horizontalSlider_3.setValue(num2) self.spinBox_4.setValue(num2) def dowm2(self,num2): self.horizontalSlider_3.setValue(num2) self.spinBox_4.setValue(num2) def mode(self): self.mode = not self.mode if self.mode: self.lineEdit_10.setText("自动") self.openmen = True # self.zidon() else: self.lineEdit_10.setText("手动") self.openmen = False ###按键切换标签内容 def zidon(self): if self.openmen == True and self.yv == False: self.lineEdit_6.setText("关闭") else: self.lineEdit_6.setText("打开") #######MP3 def baoj(self): if self.pp == False: self.label_23.setStyleSheet("background-color: rgb(255, 0, 0);border-radius:30px;") sound = load_sound("蜂鸣器哔哔响.mp3") self.player = play_sound(sound) self.lineEdit_6.setText("关闭") def nobaoj(self): self.label_23.setStyleSheet("background-color: rgb(0, 85, 0);border-radius:30px;") sound = load_sound("蜂鸣器哔哔响.mp3") player = play_sound(sound) stop_sound(player) ######来回切换图片 def zp(self): self.zp = not self.zp if self.zp: self.label_25.setPixmap(QPixmap("不下雨.png")) self.yv = True else: self.label_25.setPixmap(QPixmap("下雨.jpg")) self.yv = False # def yvzhi(self): # try: # # 将字符串转换为浮点(假设 self.wd, self.max, self.min 是值字符串) # current_temp = float(self.wd) # upper_limit = float(self.max) # lower_limit = float(self.min) # # # 判断温度是否超出阈值 # if current_temp > upper_limit or current_temp < lower_limit: # self.label_22.setStyleSheet("background-color: rgb(0, 255, 0); border-radius: 30px;") # else: # self.label_22.setStyleSheet("background-color: rgb(0, 85, 0); border-radius: 30px;") # except ValueError as e: # print(f"据格式错误: {e}") # except AttributeError as e: # print(f"属性缺失: 确保已接收到据 - {e}") ###########串口 def sx_ck(self): self.comboBox.clear() serial_ports = serial.tools.list_ports.comports() for port in serial_ports: self.comboBox.addItem(port.device) def open_serial_modbus(self): self.open_serial_flag = not self.open_serial_flag databits = int(8) stopbits = int(1) parity = serial.PARITY_NONE if self.open_serial_flag: self.pushButton_2.setText("关闭串口") self.label_2.setPixmap(QPixmap("指示灯常亮.png.png")) port = self.comboBox.currentText() baudrate = int(self.comboBox_2.currentText()) if self.serial_thread and self.serial_thread.isRunning(): self.serial_thread.terminate() self.serial_thread.wait() try: self.serial_thread = SerialThread(port, baudrate, databits,parity,stopbits) self.serial_thread.data_received.connect(self.FirstReader) self.serial_thread.start() # print(f"串口 {port} 已连接,波特率: {baudrate}") # self.plainTextEdit.appendPlainText(f"串口 {port} 已连接,波特率: {baudrate}") except Exception as e: print(f"无法连接到串口 {port}: {str(e)}") # self.plainTextEdit.appendPlainText(f"无法连接到串口 {port}: {str(e)}") else: self.pushButton_2.setText("打开串口") self.label_2.setPixmap(QPixmap("指示灯熄灭.png")) self.serial_thread.serial_client.close() # 改进后的指令发送方法 def send_custom_instruction_with_delay(self): try: # if self.hex_display == False: instruction = bytes.fromhex(str(self.plainTextEdit_2.toPlainText()))##16 self.send_protocol(instruction) # else: # instruction = str(self.plainTextEdit_2.toPlainText()).encode("GBK")##字符串 # self.send_protocol(instruction) except Exception as e: print(f"发送指令时发送错误: {e}") def send_protocol(self, protocol): if hasattr(self, 'serial_thread') and self.serial_thread.isRunning(): self.serial_thread.serial_client.write(protocol) print("协议发送成功.") else: print("串行Modbus RTU连接未打开.") def format_data(self, data): return ' '.join(f"{byte:02X}" for byte in data) def FirstReader(self, information): # if self.hex_display == False: formatted_data = self.format_data(information) # 将接收到的据格式化为十六进制 self.plainTextEdit.appendPlainText(f"接收到的信息是:{formatted_data}") # else: # self.plainTextEdit.appendPlainText(f"{information}") ##字符串 # print(f"{information}") hex_string = "这个里面填什么才解析出字符串" # 输入的十六进制字符串 # 去掉空格并解码为字节 byte_data = bytes.fromhex(hex_string.replace(" ", "")) # 使用GBK编码解码为字符串 decoded_string = byte_data.decode('GBK') print(decoded_string) ########串口读取据 # def FirstReader(self, information): # self.plainTextEdit.appendPlainText(f"{information}") # self.num1 = information.split(" ")[1].split(" ")[0] # self.num2 = information.split(" ")[2].split(" ")[0] # self.num3 = information.split(" ")[3].split(" ")[0] # self.wd = self.num1.split(" ")[0].strip(" ") # self.max = self.num2.split(" ")[0].strip(" ") # self.min = self.num3.split(" ")[0].strip(" ") # self.lineEdit_9.setText(str(self.wd)) # self.lineEdit_7.setText(str(self.max)) # self.lineEdit_8.setText(str(self.min)) # self.yvzhi() if __name__ == '__main__': warnings.filterwarnings("ignore", category=DeprecationWarning) app = QApplication([]) window = MyWindow() window.show() app.exec()
最新发布
05-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值