1. 程式人生 > >leetcode single-number

leetcode single-number

ole could subject ber 使用 代碼 [] ron lin

題目描述

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?

我的解題思路:不能使用額外空間,時間要線性,粗暴的方法就是兩個循環

在下的代碼 時間213ms 空間13164k
public class Solution {
    public int singleNumber(int[] A) {
        for (int i=0;i<A.length;i++){
            Boolean twice = false;
            for (int j= 0;j<A.length;j++){
                if (i == j)
                    continue;
                if (A[i] == A[j]){
                    twice = true;
                    break;
                }
            }
            if (!twice){
                return A[i];
            }
        }
        return 0;
    }
}

  

大神代碼 時間150ms 空間12952k 異或的思路就是好啊,兩個相同的數異或為0

public class Solution {
    public int singleNumber(int[] A) {
        int num = 0;
        for(int i=0;i<A.length;i++){
            num^=A[i];
        }
        return num;
    }
}

  

leetcode single-number