C语言/数据结构位运算题解:异或XOR找出蛋糕订单中的“VIP独特口味“——只出现一次的数字

问题描述

小明是蛋糕工厂的生产主管,工厂每天需要根据订单生产不同口味的蛋糕。订单列表中的每种口味(用整数表示)都恰好出现两次,但有一种特殊口味的蛋糕订单只出现一次(这是VIP客户的定制订单)。小明需要快速找出这个只出现一次的独特口味,以便优先安排生产。

要求:

  1. 设计一个算法,在O(n)的时间复杂度内找出只出现一次的蛋糕口味编号。
  2. 尽量减少额外空间的使用,优化资源分配效率。

测试样例

样例1:

输入:orders = [1, 1, 2, 2, 3, 3, 4, 5, 5] 输出:4 解释:口味1出现2次,2出现2次,3出现2次,4出现1次,5出现2次。因此独特口味是4。

样例2:

输入:orders = [0, 1, 0, 1, 2] 输出:2 解释:口味0出现2次,1出现2次,2出现1次。因此独特口味是2。

样例3:

输入:orders = [7, 3, 3, 7, 10] 输出:10 解释:口味7出现2次,3出现2次,10出现1次。因此独特口味是10。

约束条件

  • 1 ≤ orders.length ≤ 1001
  • 0 ≤ ordersi ≤ 1000
  • 订单数量为奇数(因为除了一种口味出现一次外,其余每种口味都恰好出现两次)
  • 输入保证只有一种口味出现一次,其余每种口味都恰好出现两次

程序代码

#include <stdio.h>

int findUnique(int* orders, int ordersSize) {

int result = 0;

for (int i = 0; i < ordersSize; i++) {

result ^= ordersi;

}

return result;

}

int main() {

int orders1\[\] = {1, 1, 2, 2, 3, 3, 4, 5, 5};

int orders2\[\] = {0, 1, 0, 1, 2};

int orders3\[\] = {7, 3, 3, 7, 10};

printf("%d\n", findUnique(orders1, 9)); // 4

printf("%d\n", findUnique(orders2, 5)); // 2

printf("%d\n", findUnique(orders3, 5)); // 10

return 0;

}

cpp 复制代码
#include <stdio.h>

int findUnique(int* orders, int ordersSize) {
    int result = 0;
    for (int i = 0; i < ordersSize; i++) {
        result ^= orders[i];
    }
    return result;
}

int main() {
    int orders1[] = {1, 1, 2, 2, 3, 3, 4, 5, 5};
    int orders2[] = {0, 1, 0, 1, 2};
    int orders3[] = {7, 3, 3, 7, 10};
    
    printf("%d\n", findUnique(orders1, 9));  // 4
    printf("%d\n", findUnique(orders2, 5));  // 2
    printf("%d\n", findUnique(orders3, 5));  // 10
    
    return 0;
}

运行结果

相关推荐
soso19681 小时前
低功耗设计与BMS开发指南
c语言·开发语言·汇编
老师我太想进步了20262 小时前
【数据结构-8】栈的实现
c语言·数据结构·算法
LCG元3 小时前
串口乱码,先算波特率误差再动代码
c语言·嵌入式
【心态好不摆烂】1 天前
数据结构基础精讲3
数据结构·算法
岑梓铭1 天前
《考研408数据结构》第七章(B树 和 B+树)复习笔记
数据结构·笔记·b树·考研·408
岑梓铭1 天前
《考研408数据结构》第八章(排序)复习笔记
数据结构·笔记
another heaven1 天前
【C/C++ 第一次跨越(上):用 C++11/14 停止制造新的旧代码】
c语言·c++·制造
another heaven2 天前
【C/C++ Ranges 是零开销抽象吗?拆开管道、惰性求值和编译期膨胀】
c语言·开发语言·c++
Code_Solitude2 天前
C语言动态内存 + 柔性数组 + 数组名退化
c语言·算法·柔性数组
Zwawa2 天前
让屏幕动起来:OLED动画效果,丝滑光标、帧动画和一只贪吃蛇
c语言·单片机·嵌入式