LeetCode OJ:Single Number

Single Number

  Total Accepted: 9511  Total Submissions: 21027 My Submissions

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?

算法思想:两个相同的数异或为0,剩下的那个就是答案

class Solution{
public:
	int singleNumber(int A[],int n){
		int t=0;
		for(int i=0;i<n;i++){
			t^=A[i];
		}
		return t;
	}
};

answer2:

class Solution {
public:
    int singleNumber(int A[], int n) {
        return accumulate(A,A+n,0,bit_xor<int>());
    }
};


你可能感兴趣的:(LeetCode,异或)