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;
}
相关推荐
墨楠。33 分钟前
数据结构学习记录-树和二叉树
数据结构·学习·算法
小唐C++39 分钟前
C++小病毒-1.0勒索
开发语言·c++·vscode·python·算法·c#·编辑器
醇醛酸醚酮酯1 小时前
Leetcode热题——移动零
算法·leetcode·职场和发展
沉默的煎蛋1 小时前
MyBatis 注解开发详解
java·数据库·mysql·算法·mybatis
Aqua Cheng.1 小时前
MarsCode青训营打卡Day10(2025年1月23日)|稀土掘金-147.寻找独一无二的糖葫芦串、119.游戏队友搜索
java·数据结构·算法
夏末秋也凉1 小时前
力扣-数组-704 二分查找
算法·leetcode
玛丽亚后1 小时前
动态规划(路径问题)
算法·动态规划
qy发大财1 小时前
平衡二叉树(力扣110)
数据结构·算法·leetcode·职场和发展
我们的五年1 小时前
【C语言学习】:C语言补充:转义字符,<<,>>操作符,IDE
c语言·开发语言·后端·学习
AI技术控1 小时前
计算机视觉算法实战——无人机检测
算法·计算机视觉·无人机