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} <= nums[i] <= 2^{31} - 1 −231<=nums[i]<=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;
}
相关推荐
mit6.82434 分钟前
bfs|栈
算法
CoderYanger2 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz2 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab
夏鹏今天学习了吗2 小时前
【LeetCode热题100(72/100)】前 K 个高频元素
leetcode
稚辉君.MCA_P8_Java2 小时前
DeepSeek 插入排序
linux·后端·算法·架构·排序算法
多多*2 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven
.YM.Z3 小时前
【数据结构】:排序(一)
数据结构·算法·排序算法
Chat_zhanggong3453 小时前
K4A8G165WC-BITD产品推荐
人工智能·嵌入式硬件·算法
百***48074 小时前
【Golang】slice切片
开发语言·算法·golang
墨染点香4 小时前
LeetCode 刷题【172. 阶乘后的零】
算法·leetcode·职场和发展