LeetCode -- Single Number III
題目描述:
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
在一個數組中,只有兩個數只出現了1次,其余數都出現了兩次。
思路:
如果空間允許,還是建議直接使用哈希表。
實現代碼:
public class Solution {
public int[] SingleNumber(int[] nums)
{
var hash = new Dictionary();
for(var i = 0;i < nums.Length; i++)
{
if(hash.ContainsKey(nums[i])){
hash[nums[i]] ++;
}
else{
hash.Add(nums[i], 1);
}
}
var ret = new List();
foreach(var k in hash.Keys){
if(hash[k] == 1){
ret.Add(k);
}
if(ret.Count == 2){
break;
}
}
return ret.ToArray();
}
}