给定N个数字,[N≤10^5],我们需要计算差值为K的总数对。[K>0和K<1e9]
输入格式:第一行包含N和K(整数)。第二行包含集合中的N个数字。所有N个数字都保证是不同的。
输出格式:一个整数,表示具有差异K的数字对的数量。
Sample Input #00:
5 2
1 5 3 4 2
Sample Output #00:
3
Sample Input #01:
10 1
363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793
Sample Output #01:
0
我已经有一个解决方案了(但我还没有能够像我希望的那样进行优化)。目前,我的解决方案在运行时得分为12/15,我想知道为什么我不能获得15/15的分数(我的另一个问题的解决方案不太高效,但却获得了所有的分数)。显然,代码是使用“Mono 2.10.1,C# 4”运行的。
那么,有人能想到更好的方法来进一步优化吗? VS分析器建议避免调用String.Split和Int32.Parse。虽然无法避免对Int32.Parse的调用,但我想我可以优化数组的标记化。
我的当前解决方案:
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace KDifference
{
class Solution
{
static void Main(string[] args)
{
char[] space = { ' ' };
string[] NK = Console.ReadLine().Split(space);
int N = Int32.Parse(NK[0]), K = Int32.Parse(NK[1]);
int[] nums = Console.ReadLine().Split(space, N).Select(x => Int32.Parse(x)).OrderBy(x => x).ToArray();
int KHits = 0;
for (int i = nums.Length - 1, j, k; i >= 1; i--)
{
for (j = 0; j < i; j++)
{
k = nums[i] - nums[j];
if (k == K)
{
KHits++;
}
else if (k < K)
{
break;
}
}
}
Console.Write(KHits);
}
}
}