C语言/数据结构位运算题解:异或XOR找出地铁规划中的“独特坐标“——只出现一次的数字

问题描述

小明所在的城市正在规划一条新的地铁线路,需要选择一个理想的位置建设火车站。城市中有多个居民区,每个居民区的位置用一个整数坐标表示。已知居民区的位置坐标中,除了一个坐标值只出现一次外,其余每个坐标值都恰好出现两次。规划部门希望火车站建在那个唯一坐标的居民区附近,以最大化覆盖独特区域的居民。

要求:

  1. 设计一个算法,在 O(n) 时间内找出唯一不重复的坐标位置,其中 n 是居民区的数量。
  2. 尽量减少额外空间的使用,以体现算法的空间效率。

测试样例

样例1:

输入:locations = [5, 2, 3, 2, 5, 3, 9] 输出:9 解释:坐标 5、2、3 都出现了两次,只有 9 出现一次,是唯一不重复的位置。

样例2:

输入:locations = [0, 10, 5, 10, 0] 输出:5 解释:坐标 0 和 10 都出现了两次,只有 5 出现一次。

样例3:

输入:locations = [100, 200, 100, 300, 200, 300, 500] 输出:500 解释:坐标 100、200、300 都出现了两次,只有 500 出现一次。

约束条件

  • 1 ≤ locations.length ≤ 1001
  • 0 ≤ locationsi ≤ 1000
  • 居民区数量为奇数
  • 除了一个坐标值只出现一次外,其余每个坐标值都恰好出现两次

程序代码

#include <stdio.h>

int findUnique(int* locations, int locationsSize) {

int result = 0;

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

result ^= locationsi;

}

return result;

}

int main() {

int locations1\[\] = {5, 2, 3, 2, 5, 3, 9};

int locations2\[\] = {0, 10, 5, 10, 0};

int locations3\[\] = {100, 200, 100, 300, 200, 300, 500};

printf("%d\n", findUnique(locations1, 7)); // 9

printf("%d\n", findUnique(locations2, 5)); // 5

printf("%d\n", findUnique(locations3, 7)); // 500

return 0;

}

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

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

int main() {
    int locations1[] = {5, 2, 3, 2, 5, 3, 9};
    int locations2[] = {0, 10, 5, 10, 0};
    int locations3[] = {100, 200, 100, 300, 200, 300, 500};
    
    printf("%d\n", findUnique(locations1, 7));  // 9
    printf("%d\n", findUnique(locations2, 5));  // 5
    printf("%d\n", findUnique(locations3, 7));  // 500
    
    return 0;
}

运行结果

相关推荐
§ꦿCFོ༉17 小时前
嵌入式八股文—C语言入门学习(四)
c语言·开发语言·学习
Pniubi19 小时前
关于算法用现成数据结构和手撕
数据结构
Severus_black1 天前
【C++初阶】Stack、Queue算法题大练兵!
c语言·c++·算法·stl
唐青枫1 天前
C 语言 strcpy() 用法详解与实战 Demo
c语言
程序猿打工仔1 天前
计算机基础(C语言)考编、专技岗
c语言·开发语言·算法
老师我太想进步了20261 天前
【数据结构-6】算法美学之单链表(1)
数据结构·算法
希望我万事顺遂1 天前
力扣hot100-滑动窗口最大值
数据结构·算法·leetcode
꧁细听勿语情꧂1 天前
二叉树余题,排序、直接插入排序、希尔排序
c语言·开发语言·数据结构·算法
是main不是漫1 天前
【双指针|LeetCode1089 复写零】巧用逆向思路,破解原地覆盖陷阱
数据结构·算法·leetcode
是main不是漫1 天前
【C++——类和对象(上)】筑基篇:以封装奠定面向对象之基
c语言·开发语言·c++