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;
}
相关推荐
yyt_cdeyyds5 分钟前
FIFO和LRU算法实现操作系统中主存管理
算法
alphaTao31 分钟前
LeetCode 每日一题 2024/11/18-2024/11/24
算法·leetcode
kitesxian40 分钟前
Leetcode448. 找到所有数组中消失的数字(HOT100)+Leetcode139. 单词拆分(HOT100)
数据结构·算法·leetcode
VertexGeek1 小时前
Rust学习(八):异常处理和宏编程:
学习·算法·rust
石小石Orz1 小时前
Three.js + AI:AI 算法生成 3D 萤火虫飞舞效果~
javascript·人工智能·算法
jiao_mrswang2 小时前
leetcode-18-四数之和
算法·leetcode·职场和发展
qystca2 小时前
洛谷 B3637 最长上升子序列 C语言 记忆化搜索->‘正序‘dp
c语言·开发语言·算法
薯条不要番茄酱2 小时前
数据结构-8.Java. 七大排序算法(中篇)
java·开发语言·数据结构·后端·算法·排序算法·intellij-idea
今天吃饺子2 小时前
2024年SCI一区最新改进优化算法——四参数自适应生长优化器,MATLAB代码免费获取...
开发语言·算法·matlab
是阿建吖!2 小时前
【优选算法】二分查找
c++·算法