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;
}

运行结果

相关推荐
启观川3 小时前
数据结构与算法 -第 3 章 常用算法-动态规划
数据结构·笔记·python·算法
wuminyu4 小时前
ForkJoinPool窃取线程在扫描其他WorkQueue时的随机采样算法与Phase线程挂起唤醒机制解析
java·linux·c语言·jvm·c++
Logic1014 小时前
C语言/数据结构欧几里得算法题解:长方形切割最大正方形——贪心划分计数
c语言·数据结构·算法·贪心算法·时间复杂度·空间复杂度·欧几里得算法
flinn_small6 小时前
三分算法:原理、实现与实战应用
数据结构·算法·三分
老王爱玩车7 小时前
文件操作从打开到缓冲区
c语言·开发语言·学习
INGNIGHT7 小时前
944 · 最大子矩阵(前缀和)
数据结构·c++·算法
All for pursuit.8 小时前
【动态规划-6】96.不同的二叉搜索树
数据结构·c++·算法·leetcode·动态规划
Zwawa8 小时前
传感器模块都在交出什么:从模拟电压到数字协议
c语言·单片机·嵌入式
信奥卷王8 小时前
[GESP202609 六级] 数组划分
数据结构·算法
程序员zgh9 小时前
C++ erase() 函数用法
c语言·开发语言·c++·学习