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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM