字符串算法——單一數(Single Number II)

問題:
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
給定一個整數數組,每個元素都出現三次,除了一個元素只出現過一次,找到那個單一數。
思路一:不考慮附加條件,可以採用暴力方法,依次對每個算法進行比較
思路二:採用異或的方法

class Solution {
    public int singleNumber(int[] nums) {
        int a = 0;
        int b = 0;
        for(int i = 0;i<nums.length;i++){
            b = (b^nums[i])&~a;
            a = (a^nums[i])&~b;
        }
        return b;
    }
}

對於出現奇數次的該類方法都可以用該方法。

發佈了42 篇原創文章 · 獲贊 2 · 訪問量 8877
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章