C语言/数据结构位运算题解:异或XOR找出游戏速通中的“独特初始能量值“——只出现一次的数字

问题描述

小M最近沉迷于《光明之魂》这款游戏,他正在进行速通挑战。游戏中有多个关卡,每个关卡都有一个初始能量值。有趣的是,除了一个关卡的初始能量值之外,所有其他关卡的初始能量值都恰好出现了两次。小M需要快速找到那个拥有独特初始能量值的关卡,以便优先突破,完成速通挑战。

要求:

  1. 设计一个算法,在时间复杂度为 O(n) 内找到独特的初始能量值,其中 n 是关卡的数量。
  2. 尽量减少额外空间的使用,以优化算法的性能。

测试样例

样例1:

输入:energies = [3, 5, 3, 5, 7, 9, 9] 输出:7 解释:初始能量值 3、5、9 都出现了两次,只有 7 出现了一次,因此 7 是独特的关卡。

样例2:

输入:energies = [10, 20, 10, 30, 20, 40, 40] 输出:30 解释:初始能量值 10、20、40 都出现了两次,只有 30 出现了一次,因此 30 是独特的关卡。

样例3:

输入:energies = [1, 2, 1, 2, 3, 4, 4, 5, 5] 输出:3 解释:初始能量值 1、2、4、5 都出现了两次,只有 3 出现了一次,因此 3 是独特的关卡。

约束条件

  • 1 ≤ energies.length ≤ 1001
  • 0 ≤ energiesi ≤ 1000
  • 关卡数量(即数组长度)为奇数
  • 除了一个初始能量值只出现一次外,其余每个初始能量值都恰好出现两次

程序代码

#include <stdio.h>

int findUnique(int* energies, int energiesSize) {

int result = 0;

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

result ^= energiesi;

}

return result;

}

int main() {

int energies1\[\] = {3, 5, 3, 5, 7, 9, 9};

int energies2\[\] = {10, 20, 10, 30, 20, 40, 40};

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

int size1 = sizeof(energies1) / sizeof(energies10);

int size2 = sizeof(energies2) / sizeof(energies20);

int size3 = sizeof(energies3) / sizeof(energies30);

printf("%d\n", findUnique(energies1, size1)); // 7

printf("%d\n", findUnique(energies2, size2)); // 30

printf("%d\n", findUnique(energies3, size3)); // 3

return 0;

}

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

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

int main() {
    int energies1[] = {3, 5, 3, 5, 7, 9, 9};
    int energies2[] = {10, 20, 10, 30, 20, 40, 40};
    int energies3[] = {1, 2, 1, 2, 3, 4, 4, 5, 5};
    
    int size1 = sizeof(energies1) / sizeof(energies1[0]);
    int size2 = sizeof(energies2) / sizeof(energies2[0]);
    int size3 = sizeof(energies3) / sizeof(energies3[0]);
    
    printf("%d\n", findUnique(energies1, size1));  // 7
    printf("%d\n", findUnique(energies2, size2));  // 30
    printf("%d\n", findUnique(energies3, size3));  // 3
    
    return 0;
}

运行结果

相关推荐
YLCHUP1 天前
【括号匹配+dp优化】题解:双端括号(brackets)_动态规划_状态优化_数学建模_贪心_性质挖掘_STLmap_C++算法竞赛
数据结构·c++·笔记·算法·数学建模·贪心算法·动态规划
郝学胜-神的一滴1 天前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
FlightYe1 天前
linux系统编程(二十一):C 语言常见坑
android·linux·运维·服务器·c语言·音视频
番茄味城市甜菜1 天前
二叉树刷题(C语言)
c语言·开发语言
.道阻且长.1 天前
Linux基础IO:理解文件以及回顾C文件接口
linux·运维·服务器·c语言·开发语言·职场和发展
derek19971 天前
软考软件设计师:主键、传递依赖和冗余,三问其实是一件事
c语言·c++·计算机网络·软件工程·学习方法
凌冰_1 天前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
拂拉氏1 天前
【知识讲解】 数据结构与算法-树状数组的认识
数据结构·算法·树状数组
djjjx.1 天前
Mysql数据库基础篇(十一):索引的常见操作、聚簇与非聚簇索引、为什么其他数据结构不能作为索引的底层结构
数据结构
落羽弦音1 天前
深入指针——指针与函数的探析
c语言·经验分享·笔记