LeetCode: Single Number

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   strong   for   ar   div   

LeetCode: Single Number

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?

地址:https://oj.leetcode.com/problems/single-number/

演算法:這題應該超簡單吧,直接異或,代碼:

 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 ^= A[i]; 7         } 8         return result; 9     }10 };

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?

地址:https://oj.leetcode.com/problems/single-number-ii/

演算法:這道題我是用數字邏輯上的想法來做的。按照題目的要求,如果各個位連續三次出現1,則該位最後位元運算的結果應該是0,現在我們設定兩個變數a和b,其中a和b中對應位中的二進位資訊用於統計這個位中1出現的次數。比如,若a,b的第一位為00,則表示第一位中1出現的次數為零次;若a,b的第一位為01,則表示第一位中1出現的次數為一次;若為10則表示1出現的次數為兩次。這樣,我們就可以根據當前的輸入來改變a,b的狀態來統計每一位中1出現的次數。具體的說,a,b狀態位按如下方式轉移:

ab 0 1
00 00 01
01 01 10
10 10 00

其中第一列表示ab所處的狀態,第一行表示輸入的狀態。比如若ab狀態為00,輸入為1,則ab的狀態轉為01。有了上述ab狀態的跳躍表,我們就可以利用數字邏輯寫出轉移後的狀態和轉移前狀態的邏輯關係,具體公式如下:

\begin{align*}&a^\prime = (\bar{x}\&a) | (x\&a\&0)|(x\&\bar{a}\&b)\\ &b^\prime=(\bar{x}\&b)|(x\&\bar{a}\&\bar{b})|(x\&\bar{a}\& b)|(x\& a\&\bar{b})\end{align*}

其中$a^\prime,b^\prime$表示轉移後的狀態,$x$表示輸入。上述公式化簡後為:

\begin{align*}&a^\prime=(\bar{x}\&a)|(x\&\bar{a}\&b)\\ &b^\prime=(\bar{x}\&b)|(x\&\bar{a}\&\bar{b})\end{align*}

有了上述的公式,代碼也就很簡單了:

class Solution {public:    int singleNumber(int A[], int n) {        int a = 0;        int b = 0;        int t_a = 0, t_b = 0;        for(int i = 0; i != n; ++i){            t_b = (~A[i] & b) | (A[i] & (~b) & (~a));            t_a = (~A[i] & a) | (A[i] & (~a) & b);            b = t_b;            a = t_a;        }        return a | b;    }};

 

LeetCode: Single Number

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.