Leetcode(136/137)Single Number-

Single Number1:
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,如果我們把兩個相同的數字異或,0與0異或是0,1與1異或也是0,那麼我們會得到0。根據這個特點,我們把數組中所有的數字都異或起來,則每對相同的數字都會得0,然後最後剩下來的數字就是那個只有1次的數字。

public class l136_single_number {
    public int singleNumber(int[] A) {
        int res=0;
        for(int num:A) res=res^num;
        return res;
    }

Single Number2:
Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

思路:
除了一個單獨的數字之外,數組中其他的數字都出現了三次,那麼還是要利用位操作 Bit Operation 來解此題。我們可以建立一個32位的數字,來統計每一位上1出現的個數,我們知道如果某一位上爲1的話,那麼如果該整數出現了三次,對3去餘爲0,我們把每個數的對應位都加起來對3取餘,最終剩下來的那個數就是單獨的數字。

 public int singleNumber2(int[] A) {
      int res=0;
      for(int i=0;i<32;i++){
          int sum=0;
          for(int j=0;j<A.length;j++){
              sum+=(A[j]>>i)&1;//如果該位存在值則&1=1;sum+1;
          }
          //某個數字出現了三次,則每一位相加必定是3或者0
          res|=(sum%3)<<i;
      }
      return res;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章