LeetCode //C - 260. Single Number III

260. Single Number III

Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.

You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

Example 1:

Input: nums = 1,2,1,3,2,5
Output: 3,5
Explanation: 5, 3 is also a valid answer.

Example 2:

Input: nums = -1,0
Output: -1,0

Example 3:

Input: nums = 0,1
Output: 1,0

Constraints:
  • 2 < = n u m s . l e n g t h < = 3 ∗ 1 0 4 2 <= nums.length <= 3 * 10^4 2<=nums.length<=3∗104
  • − 2 31 < = n u m s i < = 2 31 − 1 -2^{31} <= numsi <= 2^{31} - 1 −231<=numsi<=231−1
  • Each integer in nums will appear twice, only two integers will appear once.

From: LeetCode

Link: 260. Single Number III


Solution:

Ideas:

Use of Unsigned Type:

  • By casting xor_result to an unsigned int, we avoid the undefined behavior associated with negating the most negative integer.
  • The expression -(unsigned int)xor_result safely computes the two's complement for the unsigned value.
  • set_bit now correctly isolates the rightmost set bit without causing any runtime errors.
Code:
c 复制代码
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* singleNumber(int* nums, int numsSize, int* returnSize) {
    int xor_result = 0;
    for (int i = 0; i < numsSize; i++) {
        xor_result ^= nums[i];
    }

    // Cast to unsigned int for safe bit manipulation
    unsigned int set_bit = (unsigned int)xor_result & (-(unsigned int)xor_result);

    int num1 = 0, num2 = 0;
    for (int i = 0; i < numsSize; i++) {
        if ((nums[i] & set_bit) != 0) {
            num1 ^= nums[i];
        } else {
            num2 ^= nums[i];
        }
    }

    int* result = (int*)malloc(2 * sizeof(int));
    result[0] = num1;
    result[1] = num2;
    *returnSize = 2;

    return result;
}
相关推荐
小欣加油1 天前
leetcode56 合并区间
c++·算法·leetcode·职场和发展
lqqjuly1 天前
前沿算法深度解析(二)
人工智能·算法·机器学习
徐小夕1 天前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github
akunkuntaimei1 天前
2026年高考数学各省真题及答案(完整版)
算法·高考
Hello:CodeWorld1 天前
C 风格变参 vs C++ 变参模板:核心区别与选型指南
c语言·c++·算法
8Qi81 天前
LeetCode 516:最长回文子序列
算法·leetcode·职场和发展·动态规划
十月的皮皮1 天前
C语言学习笔记20260606- 求月份天数三种写法
c语言·笔记·学习
youngerwang1 天前
【从搬运工到协处理器:网卡芯片架构、算法、验证与边缘演进深度剖析】
网络·算法·架构·芯片
KaMeidebaby1 天前
卡梅德生物技术快报|纯化重组蛋白实操详解
人工智能·python·tcp/ip·算法·机器学习
caimouse1 天前
Reactos 第 5 章 进程与线程 — 5.8 Windows 的 APC 机制
c语言·windows