zoukankan      html  css  js  c++  java
  • [LeetCode OJ] Single Number之一 ——Given an array of integers, every element appears twice except for one. Find that single one.

     1 class Solution {
     2 public:
     3     int singleNumber(int A[], int n) {
     4         int i,j;
     5         for(i=0; i<n; i++)
     6         {
     7             for(j=i+1; j<n; j++)
     8             {
     9                 if(A[j]==A[i])
    10                 {
    11                     int temp = A[i+1];
    12                     A[i+1] = A[j];
    13                     A[j] = temp;
    14                     i++;
    15                     break;
    16                 }
    17             }
    18             if(j==n)
    19                 return A[i];    
    20         }
    21     }
    22 };

    上面的是传统方法,时间复杂度是O(n2),空间复杂度是O(1)。

    1 class Solution {
    2 public:
    3     int singleNumber(int A[], int n) {
    4         int result=0;
    5         for(int i=0; i<n; i++)
    6             result = result ^ A[i];
    7         return result;
    8     }
    9 };

    用位异或运算实现,时间复杂度和空间复杂度均为O(1).

    运用了异或运算具有交换律和结合律的性质。

    交换律: a^b = b^a

    结合律: (a^b)^c = a^(b^c)

    另外,a^a=0。

  • 相关阅读:
    hdu3487 Play with Chain
    poj3481
    [HNOI2002]营业额统计
    poj3468 A Simple Problem with Integers
    [NOI2004]郁闷的出纳员
    UVa1308 LA2572
    20130620
    poj3580
    20130618
    C++类模版学习笔记
  • 原文地址:https://www.cnblogs.com/Marrybe/p/3778998.html
Copyright © 2011-2022 走看看