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;
}
相关推荐
.道阻且长.4 小时前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
To_OC6 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
命运之光8 小时前
【C语言完整代码】就诊信息管理系统
java·c语言·开发语言
命运之光8 小时前
【C语言完整代码】图书管理系统:图书馆场景下的增删改查实战
c语言·开发语言
Forever Nore9 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR9 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
沫璃染墨10 小时前
《从零入门Linux系统篇(十五):系统工具篇·六——GDB调试器详解:从程序执行控制到高级调试技巧》
linux·运维·服务器·c语言·c++
Tisfy11 小时前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表
lucas_AI11 小时前
Q-CueGraph:你的多模态大模型会 zoom,但真的知道该看哪儿吗?
人工智能·算法