☰
C语言/数据结构位运算题解:异或XOR找出英雄队伍中的“独特战斗力“——只出现一次的数字
2026/10/7 15:33:09 网站建设 项目流程

问题描述

小强最近沉迷于一款英雄对战游戏,他需要组建一支英雄队伍来通关副本。每个英雄都有一个独特的战斗力数值,但游戏规则特殊:除了一个英雄的战斗力数值只出现一次外,其余每个战斗力数值都恰好出现两次(即有两个英雄拥有相同的战斗力)。这个独特的英雄拥有特殊的技能,能够帮助队伍轻松通关。

小强希望你能帮他快速找出这个独特战斗力数值的英雄,以便优先招募。请你设计一个高效的算法,在 O(n) 的时间复杂度内找出这个独特的数值,并尽量减少额外空间的使用。

测试样例

样例1:

输入:heroes = [5, 10, 5, 20, 10, 30, 20]输出:30解释:战斗力数值 5 出现两次(索引0和2),10 出现两次(索引1和4),20 出现两次(索引3和6),30 只出现一次(索引5),因此 30 是独特的数值。

样例2:

输入:heroes = [100, 200, 100, 300, 200, 400, 300]输出:400解释:100 出现两次(索引0和2),200 出现两次(索引1和4),300 出现两次(索引3和6),400 只出现一次(索引5),因此 400 是独特的数值。

样例3:

输入:heroes = [1, 1, 2, 2, 3, 4, 4]输出:3解释:数值 1 出现两次(索引0和1),2 出现两次(索引2和3),4 出现两次(索引5和6),3 只出现一次(索引4),因此 3 是独特的数值。

约束条件

  • 1 ≤ heroes.length ≤ 1001
  • 0 ≤ heroes[i] ≤ 1000
  • 队伍大小为奇数
  • 除了一个英雄的战斗力数值只出现一次外,其余每个战斗力数值都恰好出现两次

程序代码

#include <stdio.h>

int findUnique(int* heroes, int heroesSize) {

int result = 0;

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

result ^= heroes[i];

}

return result;

}

int main() {

int heroes1[] = {5, 10, 5, 20, 10, 30, 20};

int heroes2[] = {100, 200, 100, 300, 200, 400, 300};

int heroes3[] = {1, 1, 2, 2, 3, 4, 4};

printf("%d\n", findUnique(heroes1, 7)); // 30

printf("%d\n", findUnique(heroes2, 7)); // 400

printf("%d\n", findUnique(heroes3, 7)); // 3

return 0;

}

#include <stdio.h> int findUnique(int* heroes, int heroesSize) { int result = 0; for (int i = 0; i < heroesSize; i++) { result ^= heroes[i]; } return result; } int main() { int heroes1[] = {5, 10, 5, 20, 10, 30, 20}; int heroes2[] = {100, 200, 100, 300, 200, 400, 300}; int heroes3[] = {1, 1, 2, 2, 3, 4, 4}; printf("%d\n", findUnique(heroes1, 7)); // 30 printf("%d\n", findUnique(heroes2, 7)); // 400 printf("%d\n", findUnique(heroes3, 7)); // 3 return 0; }

运行结果

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询