LeetCode -- Single Number
題目描述:
Given an 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?
在一個數列中找到沒有重復的那一個。
思路:哈希表統計次數
實現代碼:
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.Add(nums[i],1);
}
else{
hash[nums[i]]++;
}
}
foreach(var k in hash.Keys){
if(hash[k] == 1){
return k;
}
}
return -1;
}
}