C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字

问题描述

在时尚圈的一个聚会上,每位嘉宾都穿着一种特定颜色的衣服,用整数表示颜色编号。有趣的是,除了一个颜色之外,所有的颜色都恰好被两位嘉宾穿着(形成了配对)。现在需要你帮助时尚达人小F快速找到那个穿着独特颜色衣服的嘉宾的颜色编号是什么。

要求:

  1. 设计一个算法,使其时间复杂度为 O(n),其中 n 是嘉宾的人数。
  2. 尽量减少额外空间的使用,以体现你的算法优化能力。

测试样例

样例1:

输入:colors = [1, 1, 2, 2, 3, 3, 4, 5, 5] 输出:4 解释:穿着颜色 4 的嘉宾是唯一一个没有配对的。

样例2:

输入:colors = [0, 1, 0, 1, 2] 输出:2 解释:颜色 2 只被一位嘉宾穿着,是独特的颜色。

样例3:

输入:colors = [7, 3, 3, 7, 10] 输出:10 解释:10 是聚会中唯一一个不重复的颜色编号。

约束条件

  • 1 ≤ colors.length ≤ 1001
  • 0 ≤ colorsi ≤ 1000
  • 嘉宾人数为奇数
  • 除了一个颜色只出现一次外,其余每个颜色都恰好出现两次

程序代码

#include <stdio.h>

int findUnique(int* colors, int colorsSize) {

int result = 0;

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

result ^= colorsi;

}

return result;

}

int main() {

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

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

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

int size1 = sizeof(colors1) / sizeof(colors10);

int size2 = sizeof(colors2) / sizeof(colors20);

int size3 = sizeof(colors3) / sizeof(colors30);

printf("%d\n", findUnique(colors1, size1)); // 4

printf("%d\n", findUnique(colors2, size2)); // 2

printf("%d\n", findUnique(colors3, size3)); // 10

return 0;

}

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

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

int main() {
    int colors1[] = {1, 1, 2, 2, 3, 3, 4, 5, 5};
    int colors2[] = {0, 1, 0, 1, 2};
    int colors3[] = {7, 3, 3, 7, 10};
    
    int size1 = sizeof(colors1) / sizeof(colors1[0]);
    int size2 = sizeof(colors2) / sizeof(colors2[0]);
    int size3 = sizeof(colors3) / sizeof(colors3[0]);
    
    printf("%d\n", findUnique(colors1, size1));  // 4
    printf("%d\n", findUnique(colors2, size2));  // 2
    printf("%d\n", findUnique(colors3, size3));  // 10
    
    return 0;
}

运行结果

相关推荐
可乐_不渴13 分钟前
# C语言文件操作全解析:从 fopen 到 fclose,一文吃透文件 IO
linux·服务器·c语言
m0_639906949 小时前
Redis入门|五种数据结构、使用场景、持久化RDB&AOF
数据结构·数据库·redis
2601_9707038313 小时前
工业除湿机租赁:把一份租金合同拆开看
大数据·数据结构·算法·数据库架构·推荐算法
Zwawa14 小时前
串口为什么会丢字节:从轮询到中断和环形缓冲区
c语言·单片机·嵌入式
揽星河..17 小时前
【C语言】分支和循环
c语言·c++·算法
丘山望岳18 小时前
单调栈和单调队列
数据结构
揽星河..19 小时前
【C语言】猜数字游戏
c语言·算法·游戏
UIU11421 小时前
P16237 [蓝桥杯 2026 省 B] 应急布线
数据结构·c++·算法·蓝桥杯
黎相思1 天前
BTree
数据结构·b树·b+树
听风说ml1 天前
socket编程 【C语言】
c语言·udp·tcp·socket编程