题目要求:
提供一个一维整数数组,数组内的元素取值范围为[0,520],统计输出数组内的任意两元素之和为520的个数
:::danger
限制:数组内的元素只能使用一次
:::
using System;
using System.Collections.Generic;
namespace CountNumberPairs
{
internal static class Program
{
static void Main(string[] args)
{
int[] nums = { 250,520,170,420,100,100,260 };
int count = Count(nums);
Console.WriteLine(count);
}
/*创建一个字典(初始为空),将数组中的元素与总额的差值数与字典键值对的键值进行比较;
* 存在该键值,则数量-1,计数+1;且若剩余匹配次数为0时,移除该值;
* 不存在则将该值导入字典;
*/
static int Count(int[] nums)
{
// 保护逻辑,防止传入数组为空
if (nums == null)
{
return 0;
}
int counter = 0;
var dict = new Dictionary<int, int>();
foreach (var n in nums)
{
int diff = 520 - n;
if (dict.ContainsKey(diff))
{
counter++;
/*以下两行
* if(--dict[diff]==0)
*/
dict[diff]--;
if (dict[diff] == 0)
{
dict.Remove(diff);
}
}
else
{
if (!dict.ContainsKey(n))
{
dict[n] = 0;
}
dict[n]++;
}
}
return counter;
}
}
}
using System;
using System.Collections.Generic;
namespace CountNumberPairs
{
internal static class Program
{
static void Main(string[] args)
{
int[] nums = new int[10] { 1, 9, 2, 8, 7, 3, 4, 6, 5, 5 };
int count = Count(nums,10,10);
Console.WriteLine(count);
}
static int Count(int[] nums,int k,int sum)
{
if (nums == null)
{
return 0;
}
int counter = 0;
var dict = new int[k+1];
foreach (var n in nums)
{
int diff = sum - n;
if (dict[diff]>0)
{
counter++;
dict[diff]--;
}
else
{
dict[n]++;
}
}
return counter;
}
}
}