【LeetCode】Single Number II,leetcodesingle

來源:互聯網
上載者:User

【LeetCode】Single Number II,leetcodesingle

題目

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?

解答

1.通用解法,適合出現k次的
//int型資料為32位,可以開一個大小為32的int型數組儲存N個元素的各個二進位位的1出現的次數,然後將該次數模3,
//若為1,則說明該位為所找元素二進位的對應那位,用一個初始為零的ret與找出的位作或運算,最終得到要找的數ret

public class Solution {    public int singleNumber(int[] A) {        int[] bit=new int[32];        int ret=0;        for(int i=0;i<32;i++){            for(int j=0;j<A.length;j++){                bit[i]+=(A[j]>>i)&1;            }            ret|=(bit[i]%3)<<i;        }        return ret;    }}

2.更快的解法,用3個int代表3個32位的數組,one表示出現1次的位,two表示出現2次的位,three表示出現3次的位
//(然後消除所有出現3次的位)

int singleNumber(int[] A){int one=0,two=0,three=0;for(int i=0;i<A.length;i++){two|=one&A[i];one^=A[i];three=one&two;one&=~three;two&=~three;}return one;}

---EOF---




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.