标签: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,最后得出的结果就为出现一次的数。
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
标签:app 效率比较 使用 cep 比较 res 方法 tco []
原文地址:http://www.cnblogs.com/271934Liao/p/7157510.html