C# 我的算法中的缺陷是在dista中查找每个元素的最大子数组的大小
例如,给定数组C# 我的算法中的缺陷是在dista中查找每个元素的最大子数组的大小,c#,algorithm,sorting,time-complexity,C#,Algorithm,Sorting,Time Complexity,例如,给定数组A={1,3,2,17,10},答案是3,因为集合{1,2,3}是最大的集合,因此对于集合中的一些A,集合中的每个元素都是范围[A,A+4](即A+4) 我的算法是 int[] toys = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse); Array.Sort(toys); int max_together = 0; for(int i = 0; i < toys.Le
A={1,3,2,17,10}
,答案是3
,因为集合{1,2,3}
是最大的集合,因此对于集合中的一些A
,集合中的每个元素都是范围[A,A+4]
(即A+4
)
我的算法是
int[] toys = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
Array.Sort(toys);
int max_together = 0;
for(int i = 0; i < toys.Length; ++i)
{
int plus_four = toys[i] + 4;
int j = i + 1;
for(; j < toys.Length && toys[j] <= plus_four; ++j);
int span = j - i;
if(span > max_together)
{
max_together = span;
}
}
int[]toys=Array.ConvertAll(Console.ReadLine().Split(“”),Int32.Parse);
数组。排序(玩具);
int max_=0;
对于(int i=0;i
而且它没有通过大多数测试用例
也许我读错了
我的完整解决方案是
using System;
using System.Collections.Generic;
using System.IO;
class Solution
{
static void Main(String[] args)
{
Console.ReadLine(); // N
int[] toys = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
Array.Sort(toys);
int max_together = 0;
for(int i = 0; i < toys.Length; ++i)
{
int plus_four = toys[i] + 4;
int j = i + 1;
for(; j < toys.Length && toys[j] <= plus_four; ++j);
int span = j - i;
if(span > max_together)
{
max_together = span;
}
}
Console.WriteLine(1 + (toys.Length - max_together));
}
}
使用系统;
使用System.Collections.Generic;
使用System.IO;
类解决方案
{
静态void Main(字符串[]参数)
{
Console.ReadLine();//N
int[]toys=Array.ConvertAll(Console.ReadLine().Split(“”),Int32.Parse);
数组。排序(玩具);
int max_=0;
对于(int i=0;i
在快速查看中,我发现您正在尝试查找排序数组(即1,2,3,10,17)上的最大跨度,而测试用例希望您查找给定数组(即1,3,2,17,10)上的最大跨度,即排序前的跨度。如果您购买一个重量为w1的玩具,您将免费获得重量介于[w1,w1+4]之间的所有玩具。这个问题要求你找到你需要购买的玩具的最小数量,这样你就能得到输入中的所有玩具。在这个例子中,A={1,3,2,17,10},答案是3,因为您需要购买玩具1(或2或3)、17和10
Java代码
int num[] = {1,3,2,17,10};
Arrays.sort(num);
int result=1;
int lastToy=num[0];
for(int i=1;i<n;i++)
{
if(num[i] > lastToy+4)
{
result++;
lastToy= num[i];
}
}
int num[]={1,3,2,17,10};
数组。排序(num);
int结果=1;
int lastToy=num[0];
对于(int i=1;i lastToy+4)
{
结果++;
lastToy=num[i];
}
}