題目連接:https://leetcode.com/problems/single-number-ii/java
題目:數組
Given an array of integers, every element appears three times except for one. Find that single one.app
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?post
題意:給定一整形數組,除了一個元素外的每個元素都是出現3次,讓找到那個僅出現一次的數。要求線性複雜度spa
結果直接看代碼吧,有凝視:code
public int singleNumber(int nums[]) { int result = 0; int[] wei = new int[32]; //此數組用於記錄nums中所有數各位中「1」出現的總次數 for(int i=0; i<32; i++) { for(int j=0; j<nums.length; j++) { if((nums[j] & 1<<i) != 0) { //假設num[j]第i爲非零,則該i位置上的統計數wei[i]加1 wei[i]++; } } } for(int i=0; i<32; i++) { //對wei[i]的統計結果進行還原:假設wei[i]不是3的倍數。則該singleNumber在i位置上是1 if(wei[i] % 3 != 0) { result += 1<<i; } } return result;