zoukankan      html  css  js  c++  java
  • Single Number leetcode java

    题目:

    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,不同为1。所以对所有数进行异或,得出的那个数就是single number。初始时先让一个数与0异或,然后再对剩下读数挨个进行异或。

    这里运用到异或的性质:对于任何数x,都有x^x=0,x^0=x

    代码如下:

    1     public int singleNumber(int[] A) {
    2         int result = 0;
    3         for(int i = 0; i<A.length;i++){
    4             result = result^A[i];
    5         }
    6         return result;
    7     }

     同时异或还有性质:

     交换律 A XOR B = B XOR A

     结合律 A XOR B XOR C = A XOR (B XOR C) = (A XOR B) XOR C

     自反性 A XOR B XOR B = A XOR 0 = A

    所以对于这个数组来说,因为只有一个数字是single的,所以数组可以表示为 a a b b c c d d e。 那么利用上述规律可以异或结果为 0 0 0 0 e。这样写的代码为:

    1 public static int singleNumber(int[] A) {
    2     for (int i = 1; i < A.length; i++) {
    3         A[i] ^= A[i-1];
    4     }
    5     return A[A.length-1];
    6 }

    Reference:

    http://www.cnblogs.com/hiddenfox/p/3397313.html

    http://wezly.iteye.com/blog/1120823

  • 相关阅读:
    九.Protobuf3特殊类型
    八.Protobuf3更新消息类型(添加新的字段)
    七.Protobuf3 嵌套类型
    六.Protobuf3引入其他.proto文件
    五.Protobuf3 枚举
    四.Protobuf3 缺省值
    VC 在调用main函数之前的操作
    Windows下的代码注入
    C 堆内存管理
    VC++ 崩溃处理以及打印调用堆栈
  • 原文地址:https://www.cnblogs.com/springfor/p/3870801.html
Copyright © 2011-2022 走看看