LeetCode136: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?

解题思路:

很简单的一题,直接用异或运算解决:连个相同数进行异或结果为0,0与任何数异或结果为原数

也可先进行排序再遍历排序后的数组,当某个数没有重复时,结果就是它了

也可用bitmap进行,不多说了。

实现代码:

#include <iostream>



using namespace std;

/*

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?

*/

class Solution {

public:

    int singleNumber(int A[], int n) {

        int ret = 0;

        for(int i = 0; i < n; i++)

            ret ^= A[i];

        return ret;

        

    }

};



int main(void)

{

    int arr[] = {2,4,5,5,4,1,2};

    int len = sizeof(arr) / sizeof(arr[0]);

    Solution solution;

    int once = solution.singleNumber(arr, len);

    cout<<once<<endl;

    return 0;

}

你可能感兴趣的:(LeetCode)