136.找出只出现一次的元素 Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

  1. /*
  2. Given an array of integers, every element appears twice except for one. Find that single one.
  3. */
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. namespace Solution {
  9. class Solution {
  10. // using Array.Sort O(nlogn)
  11. public int SingleNumber(int[] nums) {
  12. int num = 0;
  13. int length = nums.Length;
  14. if (length == 1) {
  15. return nums[0];
  16. }
  17. Array.Sort(nums);
  18. for (int i = 0; i < length; i += 2) {
  19. if (i + 1 < length) {
  20. if (nums[i] == nums[i + 1]) {
  21. continue;
  22. } else {
  23. num = nums[i];
  24. break;
  25. }
  26. } else {
  27. num = nums[i];
  28. break;
  29. }
  30. return num;
  31. }
  32. }
  33. // using Dictionary O(n)
  34. public int SingleNumber(int[] nums) {
  35. Dictionary<int, int> dict = new Dictionary<int, int>();
  36. foreach (var i in nums) {
  37. if (dict.ContainsKey(i)) {
  38. dict[i]++;
  39. } else {
  40. dict[i] = 1;
  41. }
  42. }
  43. int res = -1;
  44. foreach (var i in dict.Keys) {
  45. if (dict[i] == 1) {
  46. res = i;
  47. break;
  48. }
  49. }
  50. return res;
  51. }
  52. }
  53. class Program {
  54. static void Main(string[] args) {
  55. var s = new Solution();
  56. int[] arr = { 1, 2, 3, 4, 4 };
  57. var res = s.SingleNumber(arr);
  58. Console.WriteLine(res);
  59. }
  60. }
  61. }







原文地址:https://www.cnblogs.com/xiejunzhao/p/5ae566566c63953a49f7dbb286274cf5.html