# C#LeetCode刷题之#136-只出现一次的数字（Single Number）

Given a non-empty 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?

Input: [2,2,1]

Output: 1

Input: [4,1,2,1,2]

Output: 4

```public class Program {

public static void Main(string[] args) {
int[] nums = null;

nums = new int[] { 4, 1, 2, 1, 2 };
var res = SingleNumber(nums);
Console.WriteLine(res);

nums = new int[] { 2, 2, 1 };
res = SingleNumber2(nums);
Console.WriteLine(res);

nums = new int[] { 5, 9, 3, 9, 3, 2, 5 };
res = SingleNumber3(nums);
Console.WriteLine(res);

}

private static int SingleNumber(int[] nums) {
var dic = new Dictionary<int, int>();
for(var i = 0; i < nums.Length; i++) {
if(dic.ContainsKey(nums[i])) {
dic[nums[i]]++;
} else {
dic[nums[i]] = 0;
}
}
foreach(var item in dic) {
if(item.Value == 0) {
return item.Key;
}
}
return 0;
}

private static int SingleNumber2(int[] nums) {
var table = new Hashtable();
for(var i = 0; i < nums.Length; i++) {
if(table.ContainsKey(nums[i])) {
table.Remove(nums[i]);
} else {
}
}
var enumerator = table.Values.GetEnumerator();
enumerator.MoveNext();
return (int)enumerator.Current;
}

private static int SingleNumber3(int[] nums) {
var result = 0;
foreach(var num in nums) {
result ^= num;
}
return result;
}

}```

```4
1
2```

SingleNumber3的解法分析参考我的另一篇博文 C#LeetCode刷题之#268-缺失数字（Missing Number）