原題地址:https://leetcode-cn.com/problems/single-number/
給定一個非空整數(shù)數(shù)組,除了某個元素只出現(xiàn)一次以外,其余每個元素均出現(xiàn)兩次。找出那個只出現(xiàn)了一次的元素。
說明:
你的算法應(yīng)該具有線性時間復(fù)雜度。 你可以不使用額外空間來實現(xiàn)嗎?
示例1:
輸入: [2,2,1]
輸出: 1
示例 2:
輸入: [4,1,2,1,2]
輸出: 4
思路分析:
首先題目要求算法具有線性復(fù)雜度,所以是時間復(fù)雜度為O(n),簡單粗暴的循環(huán)嵌套就不符合要求;不使用額外空間,所以空間復(fù)雜度為O(1)。這就要求對數(shù)組本身進行操作,且不能進行循環(huán)嵌套比較,只能左右相比或者對所有數(shù)字進行操作。最后只有1個元素只出現(xiàn)一次,其余每個元素均出現(xiàn)兩次。
其實如果你熟悉位運算的規(guī)則,那這題很快就可以得出結(jié)果。異或運算有這樣一個特征,兩個相同的數(shù)異或得0;0和任何數(shù)異或都等于那個數(shù)。用表達式說明就是:
0^0=0;
1^1=0;
0^n=n (n為任何正整數(shù));
n^0=n (n為任何正整數(shù));
如此一來,只需要遍歷數(shù)組,將所有數(shù)字都進行疑惑運算,最后的結(jié)果就是那個“單身狗”。且時間復(fù)雜度為0(n),空間復(fù)雜度為O(1);
代碼實現(xiàn):
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;
}
}
小小拓展:
如果忽略限制條件的話,可以根據(jù)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中已有相同數(shù)字,則add方法會返回false
resultSet.remove(nums[i]); // 刪除重復(fù)的數(shù)字
}
}
return resultSet.iterator().next(); // 將只出現(xiàn)一次的數(shù)字輸出
}
}
觀察HashSet源碼后可以知道,add方法的實現(xiàn)是:
/**
* 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元素時,會調(diào)用putVal(),resize()等時間復(fù)雜度為O(n^2),所以不符合該題要求。