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?
题目:有一个整形数组,数组中只存在一个整数只出现一次,其他的整数的个数都出现三次,找出只出现一次的数
public class LeetCode1 {
// 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?
// 你的算法应该有一个线性运行时的复杂性。你能实现它不使用额外的内存吗?
public static int singleNumber(int[] nums) {
int length = nums.length;
TreeMap<Integer,Integer> map = new TreeMap<Integer, Integer>();
for(int i = 0 ;i < length;i++){
if(null == map.get(nums[i])){
map.put(nums[i], 1);
continue;
}
if(map.get(nums[i]) == 1){
map.put(nums[i],2);
continue;
}
if(map.get(nums[i]) == 2){
map.remove(nums[i]);
}
}
int num = map.firstKey();
return num;
}
public static void main(String[] args){
//int[] nums = {3,3,1,3,5,5,6,6,5,7,7,7,6};
int[] nums = {2,2,3,2};
int num = singleNumber(nums);
System.out.println(num);
}
}
我又一次选择了用treemap来进行操作
之前有一题是一个整型数组中的数据,只有一个数字出现一次,其他的数字都出现两次,找出只出现一次的数字。我也是采用的使用treemap的方式,两者用的时间差不多。后来发现在可以使用异或运算,两个相同的数进行异或的结果为0,如果三个相同的数进行异或,结果为这个数本身,那么在一个几乎都是两个相同的数组成的数组中找出,只出现一次的数,则可以使用对所有的数进行异或的操作,这样得到的结果即为只出现一次的数。
int x = 123;
int y = x^x;
此时y的值为0;
int y = x^x^x;
此时y的值为x;