题目要求:
    提供一个一维整数数组,数组内的元素取值范围为[0,520],统计输出数组内的任意两元素之和为520的个数 :::danger 限制:数组内的元素只能使用一次 :::

    1. using System;
    2. using System.Collections.Generic;
    3. namespace CountNumberPairs
    4. {
    5. internal static class Program
    6. {
    7. static void Main(string[] args)
    8. {
    9. int[] nums = { 250,520,170,420,100,100,260 };
    10. int count = Count(nums);
    11. Console.WriteLine(count);
    12. }
    13. /*创建一个字典(初始为空),将数组中的元素与总额的差值数与字典键值对的键值进行比较;
    14. * 存在该键值,则数量-1,计数+1;且若剩余匹配次数为0时,移除该值;
    15. * 不存在则将该值导入字典;
    16. */
    17. static int Count(int[] nums)
    18. {
    19. // 保护逻辑,防止传入数组为空
    20. if (nums == null)
    21. {
    22. return 0;
    23. }
    24. int counter = 0;
    25. var dict = new Dictionary<int, int>();
    26. foreach (var n in nums)
    27. {
    28. int diff = 520 - n;
    29. if (dict.ContainsKey(diff))
    30. {
    31. counter++;
    32. /*以下两行
    33. * if(--dict[diff]==0)
    34. */
    35. dict[diff]--;
    36. if (dict[diff] == 0)
    37. {
    38. dict.Remove(diff);
    39. }
    40. }
    41. else
    42. {
    43. if (!dict.ContainsKey(n))
    44. {
    45. dict[n] = 0;
    46. }
    47. dict[n]++;
    48. }
    49. }
    50. return counter;
    51. }
    52. }
    53. }
    1. using System;
    2. using System.Collections.Generic;
    3. namespace CountNumberPairs
    4. {
    5. internal static class Program
    6. {
    7. static void Main(string[] args)
    8. {
    9. int[] nums = new int[10] { 1, 9, 2, 8, 7, 3, 4, 6, 5, 5 };
    10. int count = Count(nums,10,10);
    11. Console.WriteLine(count);
    12. }
    13. static int Count(int[] nums,int k,int sum)
    14. {
    15. if (nums == null)
    16. {
    17. return 0;
    18. }
    19. int counter = 0;
    20. var dict = new int[k+1];
    21. foreach (var n in nums)
    22. {
    23. int diff = sum - n;
    24. if (dict[diff]>0)
    25. {
    26. counter++;
    27. dict[diff]--;
    28. }
    29. else
    30. {
    31. dict[n]++;
    32. }
    33. }
    34. return counter;
    35. }
    36. }
    37. }