原题地址:https://leetcode-cn.com/problems/single-number/
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
思路分析:
首先题目要求算法具有线性复杂度,所以是时间复杂度为O(n),简单粗暴的循环嵌套就不符合要求;不使用额外空间,所以空间复杂度为O(1)。这就要求对数组本身进行操作,且不能进行循环嵌套比较,只能左右相比或者对所有数字进行操作。最后只有1个元素只出现一次,其余每个元素均出现两次。
其实如果你熟悉位运算的规则,那这题很快就可以得出结果。异或运算有这样一个特征,两个相同的数异或得0;0和任何数异或都等于那个数。用表达式说明就是:
0^0=0;
1^1=0;
0^n=n (n为任何正整数);
n^0=n (n为任何正整数);
如此一来,只需要遍历数组,将所有数字都进行疑惑运算,最后的结果就是那个“单身狗”。且时间复杂度为0(n),空间复杂度为O(1);
代码实现:
class Solution {
public int singleNumber(int[] nums) {
int n = nums.length;
int result = 0;
for(int i =0;i<n;i++) {
result = result^nums[i];
}
return result;
}
}
小小拓展:
如果忽略限制条件的话,可以根据HashSet的元素唯一性进行解题,代码如下:
class Solution {
public int singleNumber(int[] nums) {
HashSet<Integer> resultSet = new HashSet<>();
int n = nums.length;
for(int i =0;i<n;i++) {
(!resultSet.add(nums[i])) { // add成功返回true,如果set中已有相同数字,则add方法会返回false
resultSet.remove(nums[i]); // 删除重复的数字
}
}
return resultSet.iterator().next(); // 将只出现一次的数字输出
}
}
观察HashSet源码后可以知道,add方法的实现是:
/**
* Adds the specified element to this set if it is not already present.
* More formally, adds the specified element <tt>e</tt> to this set if
* this set contains no element <tt>e2</tt> such that
* <tt>(e==null ? e2==null : e.equals(e2))</tt>.
* If this set already contains the element, the call leaves the set
* unchanged and returns <tt>false</tt>.
*
* @param e element to be added to this set
* @return <tt>true</tt> if this set did not already contain the specified
* element
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
而put方法的源码是:
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
可以看出,hashset在add元素时,会调用putVal(),resize()等时间复杂度为O(n^2),所以不符合该题要求。