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

运行结果

相关推荐
2401_839080544 小时前
C++常见八股
数据结构·c++·算法
暮雨封夕5 小时前
跳表(Skip List)详解:原理、实现、使用场景与实际应用
数据结构
miller-tsunami5 小时前
排序的相关知识点
数据结构·排序算法
Escalating_xu5 小时前
【C 语言项目】数组和函数综合实践:从零实现控制台扫雷游戏
c语言
Navigator_Z8 小时前
LeetCode //C - 1254. Number of Closed Islands
c语言·算法·leetcode
Logic1019 小时前
C语言/数据结构滑动窗口题解:替换k个字符后的最长连续相同字符子串(LeetCode 424)
c语言·数据结构·字符串·滑动窗口·时间复杂度·频率统计·算法题
free-elcmacom10 小时前
发际线警告!手撕《C陷阱与缺陷》终极 BOSS:signal 函数与 typedef 魔法
c语言·开发语言·visual studio code·visual studio
程序员阿鹏10 小时前
简单介绍一下软引用
java·开发语言·jvm·数据结构·后端
haluhalu.11 小时前
初识 Protobuf:微服务跨语言通信的一份契约
java·c语言·开发语言·c++·python