有N个数,其中2个数出现了奇数次(这两个数不相等),其他数都出现偶数次,问用O(1)的空间复杂度,找出这两个数,不需要知道具体位置,只需要知道这两个值。

本文介绍了一种算法,该算法通过计算异或(xor)来找出包含重复元素的数组中的两个非重复数。首先计算整个数组的异或值,然后找出异或结果中最右侧的设置位,接着将数组分为两组并分别计算每组的异或值,最终得到两个非重复数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* This finction sets the values of *x and *y to nonr-epeating
 elements in an array arr[] of size n*/
void get2NonRepeatingNos(int arr[], int n, int *x, int *y)
{
    int xor = arr[0]; /* Will hold xor of all elements */
    int set_bit_no;  /* Will have only single set bit of xor */
    int i;
    *x = 0;
    *y = 0;

    /* Get the xor of all elements */
    for(i = 1; i < n; i++)
        xor ^= arr[i];

    /* Get the rightmost set bit in set_bit_no */
    set_bit_no = xor & ~(xor-1);   //xor&(-xor)   or  xor&(~xor+1)

    /* Now divide elements in two sets by comparing rightmost set
     bit of xor with bit at same position in each element. */
    for(i = 0; i < n; i++)
    {
        if(arr[i] & set_bit_no)
            *x = *x ^ arr[i]; /*XOR of first set */
        else
            *y = *y ^ arr[i]; /*XOR of second set*/
    }
}
http://www.geeksforgeeks.org/find-two-non-repeating-elements-in-an-array-of-repeating-elements/
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值