#82 Single Number

本文介绍了一种使用异或运算寻找数组中唯一出现一次的数字的方法。对于2*n+1个数,除了一个数字只出现一次外,其余数字均出现两次。通过一过式遍历并利用异或操作实现高效查找。

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

题目描述:

Given 2*n + 1 numbers, every numbers occurs twice except one, find it.

Example

Given [1,2,2,1,3,4,3], return 4

Challenge 

One-pass, constant extra space.

题目思路:

这题我就用了很多人用的bit manipulate的方法,用异或来解决。因为当两个数相同的时候,异或返回0,所以把A中所有数都异或一遍,最后得到的数就是那个单身狗,因为没有别的数跟它异或成0。

Mycode(AC = 10ms):

class Solution {
public:
	/**
	 * @param A: Array of integers.
	 * return: The single number.
	 */
    int singleNumber(vector<int> &A) {
        // write your code here
        if (A.size() == 0) return 0;
        else if (A.size() == 1) {
            return A[0];
        }
        else {
            int bitm = A[0];
            for (int i = 1; i < A.size(); i++) {
                bitm ^= A[i];
            }
            
            return bitm;
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值