在线提交: https://leetcode.com/problems/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?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
思路:使用Dictionary<int, int>存储每一个整数出现的次数即可,然后从里面挑出第一个出现次数为1的KeyValuePair的Key值。
已AC代码:
public class Solution {
public int SingleNumber(int[] nums) {
int res = 0;
Dictionary<int, int> dict = new Dictionary<int, int>();
foreach (var num in nums)
{
if (!dict.ContainsKey(num))
{
dict.Add(num, 1);
}
else
dict[num]++;
}
res = dict.FirstOrDefault(kv => kv.Value == 1).Key;
return res;
}
}