標籤:app 效率比較 使用 cep 比較 res 方法 tco []
題目:Given an array of integers, every element appears twice except for one. Find that single one.
題意及分析:一個數組中,有一個數只出現了一次,其他的出現了兩次。要求給出只出現一次的數。這道題,最簡單的方法是用一個hashtable來儲存,然後得出結果,但是效率比較低。也可以用位元運算求解。直接使用異或運算,因為對於異或運算有:n^0=n,n^n=0,所以相同的數異或為0,最後得出的結果就為出現一次的數。
位元運算常用技巧:(1)n & (n-1)能夠消滅n中最右側的一個1。(2) 右移:除以2, 左移:乘以2。(3)異或性質:交換律,0^a=a, a^a=0;
使用hashtable,主要是看hashtable怎麼遍曆:
import java.util.Enumeration;import java.util.Hashtable;public class Solution { public int singleNumber(int[] nums) { if(nums.length==0) return 0; Hashtable<Integer,Integer> res = new Hashtable<>(); for(int i=0;i<nums.length;i++){ if(!res.containsKey(nums[i])){ res.put(nums[i],1); } else{ res.remove(nums[i]); res.put(nums[i],2); } } Enumeration e = res.keys(); while( e.hasMoreElements() ){ Object x =e.nextElement(); if(res.get(x)==1){ return (int)x; } } return 0; }}
使用位元運算:
public class Solution { public int singleNumber(int[] nums) { if(nums.length==0) return 0; int res=0; for(int i=0;i<nums.length;i++){ res = res^nums[i]; } return res; }}
[LeetCode] 136.Single Number Java