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].
思路:
如果空间允许,还是建议直接使用哈希表。
实现代码:
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(); } }
?