一群马,返回马数值差值最小的数
一开始想到是穷举暴力,但是超时了。
后来想着先排序,去整了快速排序如下
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Solution
{
static void Main(string[] args)
{
int N = int.Parse(Console.ReadLine());
int[] pi = new int[N+1];
for (int i = 1; i <= N; i++)
{
pi[i] = int.Parse(Console.ReadLine());
}
Qsort (pi,1,N);
int sm=pi[2]-pi[1];
for(int i=2;i <= N;i++)
{
if(pi[i]-pi[i-1]< sm){sm=pi[i]-pi[i-1];}
}
// Write an answer using Console.WriteLine()
// To debug: Console.Error.WriteLine("Debug messages...");
Console.WriteLine(sm);
}
static void Qsort (int[] a,int low,int high){
if(low<high)
{
int i=low;
int j=high;
a[0] = a[low];
while(low < high){
while(a[high]>a[0] && low < high){
if (a[0]<= a[high]){
--high;
}else{a[low]=a[high];break;}
}
while(a[low]<a[0] && low < high){
if (a[0] > a[low]){
++low;
}else{a[high]=a[low];break;}
}
}
a[low] =a[0];
Qsort (a,i,low-1);
Qsort (a,high+1,j);
}
}
}
虽然能过其中几个测试,但是数量>10就还是超时(这里O(nlogn)),先放着吧,之后尝试别的排序
反正浪费的空间也不是我的空间是吧(笑)
大半年过去了
来填坑
我以前真捞
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Solution
{
static void Main(string[] args)
{
int diff;
int N = int.Parse(Console.ReadLine());
int[] pi = new int[N];
for (int i = 0; i < N; i++)
{
pi[i] = int.Parse(Console.ReadLine());
Console.Error.WriteLine(pi[i]);
}
Array.Sort(pi);
// Write an answer using Console.WriteLine()
// To debug: Console.Error.WriteLine("Debug messages...");
diff = pi[1]-pi[0];
for(int i =2 ;i<N;i++){
if(diff>pi[i]-pi[i-1])diff =pi[i]-pi[i-1];
}
Console.WriteLine(diff);
}
}
直接解决了