標籤:數組 數字 演算法 面試 java
【137-Single Number II(只出現一次的數字II)】
【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】
原題
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?
題目大意
給一個數組,裡面只有一個數字一次,其它數字都出現3次,找出這個出現一次的數字,要求時間複雜度為O(n),空間複雜度為O(1)。最好不傅額外的空間。
解題思路
方法一:考慮全部用二進位表示,如果我們把 第ith個位置上所有數位和對3取餘,那麼只會有兩個結果 0 或 1 (根據題意,3個0或3個1相加餘數都為0). 因此取餘的結果就是那個 “Single Number”。一個直接的實現就是用大小為 32的數組來記錄所有位上的和。
方法二:使用掩碼變數:
ones 代表第ith位只出現一次的掩碼變數
twos 代表第ith位只出現兩次次的掩碼變數
threes 代表第ith位只出現三次的掩碼變數
當第ith位出現3次時,我們就ones和twos的第ith位設定為0. 最終的答案就是 ones。
代碼實現
演算法實作類別
public class Solution { public int singleNumber(int[] nums) { int[] count = new int[32]; int result = 0; for (int i = 0; i < 32; i++) { for (int n : nums) { // 統計第i位的1的個數 if (((n >> i) & 1) == 1) { count[i]++; } } result |= (count[i] % 3) << i; } return result; } public int singleNumber2(int[] nums) { // 只出現一次的掩碼變數, int ones = 0; // 只出現兩次次的掩碼變數 int twos = 0; // 只出現三次的掩碼變數 int threes; for (int n : nums) { twos |= ones & n; // 異或3次 和 異或 1次的結果是一樣的 ones ^= n; // 對於ones和twos把出現了3次的位置設定為0(取反之後1的位置為0) threes = ones & twos; ones &= ~threes; twos &= ~threes; } return ones; }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明
歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47745445】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
【LeetCode-面試演算法經典-Java實現】【137-Single Number II(隻字出一次的數字II)】