136. Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Subscribe to see which companies asked this question
题意:给定一个数组,数组中除了一个元素,其他元素都有两个。找到那个唯一的元素。
public class Solution {
public int singleNumber(int[] nums) {
HashSet<Integer> set = new HashSet<Integer>();
for(int i = 0; i <nums.length; i++){
if(!set.contains(nums[i])){
set.add(nums[i]);
}else{
set.remove(nums[i]);
}
}
int m =set.hashCode();
return m;
}
}
使用哈希表做出来的时候,哥哥是很高兴的,但是看到有些人用到了位运算求解,发现世界真大……
int singleNumber(int A[], int n) {
int result = 0;
for (int i = 0; i<n; i++)
{
result ^=A[i];
}
return result;
}
简直完美……
原文链接:https://leetcode.com/problems/single-number/