zoukankan      html  css  js  c++  java
  • [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?

     分析:用下列multiset时间复杂度O(n),空间复杂度O(n),因为额外用的multiset的大小和数组大小相同。

    #include<set>
    using namespace std;
    
    class Solution {
    public:
        int singleNumber(int A[], int n) {
            multiset<int> ms;
            for(int i=0;i<n;i++)
                ms.insert(A[i]);
            for(int i = 0;i<n;i++)
            {
              int num = ms.count(A[i]);
              if(num == 1)
                  return A[i];
            }
        }
    };

     分析:用“异或的方法”,原理是:两个相同的数异或等于0,0和任意数A异或等于A。

    class Solution {
    public:
        int singleNumber(int A[], int n) {
            int a=0;
            for(int i=0;i<n;i++)
               a = a^A[i];
               return a;
        }
    };
  • 相关阅读:
    第八章
    第十章
    第九章
    第七章
    第六章
    第五章
    第四章心得
    第二章心得
    第三章心得
    第一章心得
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3779237.html
Copyright © 2011-2022 走看看