map(dictionary)
public class Solution {
public int SingleNumber(int[] nums) {
int result = 0;
Dictionary <int, int> dic = new Dictionary <int, int> ();
foreach (int i in nums) {
if(dic.ContainsKey(i)) {
dic[i] ++;
}
else {
dic.Add(i,1);
}
}
foreach (int key in dic.Keys) {
if(dic[key] == 1)
result = key;
}
return result;
}
}
排序,消除(排序超时)
public class Solution {
public int SingleNumber(int[] nums) {
int result = 0;
Array.Sort(nums);
int i = 0;
while(i<nums.Length) {
if(i != nums.Length-1) {
if(nums[i] == nums[i+1])
i += 2;
else {
result = nums[i];
break;
}
}
else {
result = nums[nums.Length-1];
}
}
return result;
}
}
异或
public class Solution {
public int SingleNumber(int[] nums) {
int result = 0;
for (int i = 0; i < nums.Length; i++)
result ^= nums[i];
return result;
}
}
public class Solution {
public int SingleNumber(int[] nums) {
return nums.Aggregate((a,b)=>a^b);
}
}