ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

C语言/数据结构位运算题解:异或XOR找出英雄队伍中的“独特战斗力“——只出现一次的数字

C语言/数据结构位运算题解:异或XOR找出英雄队伍中的“独特战斗力“——只出现一次的数字 问题描述小强最近沉迷于一款英雄对战游戏他需要组建一支英雄队伍来通关副本。每个英雄都有一个独特的战斗力数值但游戏规则特殊除了一个英雄的战斗力数值只出现一次外其余每个战斗力数值都恰好出现两次即有两个英雄拥有相同的战斗力。这个独特的英雄拥有特殊的技能能够帮助队伍轻松通关。小强希望你能帮他快速找出这个独特战斗力数值的英雄以便优先招募。请你设计一个高效的算法在 O(n) 的时间复杂度内找出这个独特的数值并尽量减少额外空间的使用。测试样例样例1输入heroes [5, 10, 5, 20, 10, 30, 20]输出30解释战斗力数值 5 出现两次索引0和210 出现两次索引1和420 出现两次索引3和630 只出现一次索引5因此 30 是独特的数值。样例2输入heroes [100, 200, 100, 300, 200, 400, 300]输出400解释100 出现两次索引0和2200 出现两次索引1和4300 出现两次索引3和6400 只出现一次索引5因此 400 是独特的数值。样例3输入heroes [1, 1, 2, 2, 3, 4, 4]输出3解释数值 1 出现两次索引0和12 出现两次索引2和34 出现两次索引5和63 只出现一次索引4因此 3 是独特的数值。约束条件1 ≤ heroes.length ≤ 10010 ≤ heroes[i] ≤ 1000队伍大小为奇数除了一个英雄的战斗力数值只出现一次外其余每个战斗力数值都恰好出现两次程序代码#include stdio.hint 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)); // 30printf(%d\n, findUnique(heroes2, 7)); // 400printf(%d\n, findUnique(heroes3, 7)); // 3return 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; }运行结果
返回列表