LeetCode:Single Number

来源:互联网 发布:阿里云服务器出现宕机 编辑:程序博客网 时间:2024/05/16 18:41


题目:

       

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 res = 0;        for(int i=0;i<n;++i)            res ^=A[i];        return res;    }};


解法二.

       对于数组中所有的元素,我们将其用二进制表示出来,每行为原数组的一个元素,从上到下


观察一列元素0和1出现的次数,现假设一列中1出现的次数为cnt,如果cnt能整除2,则所要求的元素


此位的二进制是0,否则是1.此算法的时间复杂度为O(n),不过常系数是32,即O(32n),相比O(n^2)


要好一点,比O(nlgn)又逊色了不少,写出这种解法只是提供一个思路.


解题代码:

class Solution {public:    int singleNumber(int A[], int n)     {        int res = 0;        for(int i=0;i<32;++i)        {            int tmp = 1 << i , cnt = 0 ;            for(int j=0;j<n;++j)                if(A[j] & tmp)                    ++cnt;            res |= cnt % 2 ? (1 << i) : (0 << i) ;        }        return res;    }};




解法三

      此方法与第二种方法类似,不过,这里不是把数组元素看成是二进制数,而是直接看成是十进制,


这样,时间复杂度也为O(n),不过常系数优化成了10,比起第二种效率提升了不少,当n > 1024,此


方法比O(nlgn)的方法还快.


解题代码:


class Solution {public:    int singleNumber(int A[], int n)     {        int div[11] = { 1 } ,res = 0;        for(int i=1;i<=10;++i)            div[i] = div[i-1] * 10 ;        int cnt = 0 ;        for(int i=0;i<n;++i)            cnt +=A[i] < 0 ;        for(int i=1;i<=10;++i)        {            int hash[10] = { 0 } ;            for(int j=0;j<n;++j)                ++hash[abs((long long)A[j])/div[i-1]%10];            for(int j=0;j<10;++j)            {                if(hash[j]%2)                    res = j * div[i-1] + res ;            }        }        res *= cnt % 2 ? -1 : 1 ;        return res;    }};




0 0
原创粉丝点击