【leetcode刷题笔记】Single Number

题目:

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

 

看了别人的解答才会的,利用公式a XOR b XOR a = b,从A[n]开始,依次往前执行A[n] = A[n] XOR A[n-1],最后A[0]就是答案。

例如如果序列是{a,b,a,c,b}

那么数组A各项分别是:

01234
c XOR a XOR a = cc XOR b XOR a XOR b = c XOR ac XOR b XOR ac XOR bb

代码:

class Solution {
public:
    int singleNumber(int A[], int n) {
        while(--n){
                A[n-1] ^= A[n];
            }
            return A[0];
    }
};

这里自己还犯了一个白痴想法,认为a XOR b要么是0要么是1,这个只是对于a,b为0,1的时候成立的,如果a,b不是0,1,此时是把a,b表示成二进制数后逐位异或的。

Java版本代码:

1 public class Solution {
2     public int singleNumber(int[] A) {
3         int answer = 0;
4         for(int i = 0;i < A.length;i++){
5             answer = answer ^ A[i];
6         }
7         return answer;
8     }
9 }

 

转载于:https://www.cnblogs.com/sunshineatnoon/p/3636727.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值