【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各项分别是:

0 1 2 3 4
c XOR a XOR a = c c XOR b XOR a XOR b = c XOR a c XOR b XOR a c XOR b b

代码:

复制代码
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 }
复制代码

 

posted @   SunshineAtNoon  阅读(176)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示