1. 程式人生 > >137.Single Number II

137.Single Number II

cnblogs 耗時 get html -i scrip details 每一個 [0

題目鏈接:https://leetcode.com/problems/single-number-ii/description/

題目大意:給出一串數,每個數都出現三次,只有一個數只出現一次,把這個出現一次的數找出來。

法一:利用hashMap,空間換時間,但是好像也沒怎麽換到時間。代碼如下(耗時15ms):

技術分享
 1     public int singleNumber(int[] nums) {
 2         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
 3         int ans = -1;
4 for(int i = 0; i < nums.length; i++) { 5 if(map.containsKey(nums[i])) { 6 map.put(nums[i], map.get(nums[i]) + 1); 7 } 8 else { 9 map.put(nums[i], 1); 10 } 11 } 12 for(int i = 0; i < nums.length; i++) {
13 if(map.get(nums[i]) == 1) { 14 ans = nums[i]; 15 break; 16 } 17 } 18 return ans; 19 }
View Code

法二:先排序,再一一計算。代碼如下(耗時5ms):

技術分享
 1     public int singleNumber(int[] nums) {
 2         Arrays.sort(nums);
 3         int ans = nums[0];
4 int cnt = 1; 5 int length = nums.length; 6 for(int i = 1; i < length; i++) { 7 if(nums[i] != nums[i - 1]) { 8 if(cnt == 1) { 9 break; 10 } 11 ans = nums[i]; 12 cnt = 1; 13 } 14 else { 15 cnt++; 16 } 17 } 18 return ans; 19 }
View Code

法三(借鑒):利用位運算,這個方法是普遍方法,136題也可以用這個方法做,但是時間復雜度其實是o(n^2),所以也不是最優的,只是用到了位運算。借鑒自:http://blog.csdn.net/feliciafay/article/details/19004479。代碼如下(耗時7ms):

技術分享
 1     public int singleNumber(int[] nums) {
 2         int ans = 0;
 3         int length = nums.length;
 4         //將每一個數取二進制位按位相加,如果都是重復的則當前位的相加和一定是3的倍數,否則當前位一定存在於要找的那個數中
 5         //比如1,1,1,2,2,2,3這六個數將其轉為二進制數按位相加,然後每一位都對3取模,最後一定可以得到3
 6         for(int i = 0; i < 32; i++) {//計算每一位
 7             int sum = 0;//統計每一位的和
 8             for(int j = 0; j < length; j++) {//對每個數取第i位的數值
 9                 if(((nums[j] >> i) & 1) == 1) {//取第i位的數值
10                     sum++;//將每個數第i位的值相加求和
11                     sum %= 3;
12                 }
13             }
14             if(sum != 0) {//如果對3取模後非0,則說明當前位一定是要找的數的某一位
15                 ans |= sum << i;//將其轉為十進制加入結果當中
16             }
17         }
18         return ans;
19     }
View Code

法四(借鑒):這個位運算還沒看懂。https://www.cnblogs.com/yangrouchuan/p/5323327.html

137.Single Number II