I have done Microsoft's interview questions. Pigeon nest principle.
Using system;
Using system. LINQ;
Using system. Collections. Generic;
Namespace consoleapplication1
{
Class Program
{
Static random Rand = new random ();
Static void main (string [] ARGs)
{
Int COUNT = 10000;
List <int> input = new list <int> ();
For (INT I = 0; I <count; I ++)
{
Input. Add (RAND. Next (Int. minvalue, Int. maxvalue ));
}
Ulong Re = pigeonnest (input, ulong. maxvalue );
Console. writeline (re );
Console. writeline ("-------------");
Console. Read ();
}
// Pigeon nest principle.
Static ulong pigeonnest (list <int> list, ulong minresult)
{
Switch (list. Count)
{
Case 0:
Case 1:
Return minresult;
Case 2:
Return ABS (list [0], list [1]);
Default:
Break;
}
Int min = List. Min ();
// Determine the bucket size.
Int width = (INT) math. Ceiling (double) (List. Max ()-min)/list. Count );
// It cannot be smaller than 1.
If (width = 1) {return 1ul ;}
// Throw data into the bucket.
Dictionary <int, numbersinfo> eachnestnum = new dictionary <int, numbersinfo> ();
Foreach (int n in List)
{
Int key = convert. toint32 (math. Ceiling (double) (N-min)/width ));
If (! Eachnestnum. containskey (key ))
{
Eachnestnum. Add (Key, new numbersinfo (key ));
}
Eachnestnum [Key]. Add (N );
}
// Locate the maximum and minimum distance between all buckets and the adjacent two buckets.
Foreach (INT key in eachnestnum. Keys)
{
Minresult = min (minresult, eachnestnum [Key]. minresult (eachnestnum, minresult ));
}
Return minresult;
}
Class numbersinfo
{
Public numbersinfo (int K)
{Key = K ;}
Private list <int> List = new list <int> ();
Private int key;
Public int max = int. minvalue;
Public int min = int. maxvalue;
Public int count {get {return list. Count ;}}
Public ulong minresult (Dictionary <int, numbersinfo> eachnestnum, ulong re)
{
// Select the smallest of the three numbers.
// Recursive this process when the number of hits is greater than 1. Due to rapid convergence, the complexity is negligible.
If (list. Count> 1)
{
Re = pigeonnest (list, RE );
}
If (eachnestnum. containskey (key-1 ))
{
Re = min (ABS (eachnestnum [Key]. Min, eachnestnum [key-1]. max), Re );
}
If (eachnestnum. containskey (Key + 1 ))
{
Re = min (ABS (eachnestnum [Key]. Max, eachnestnum [Key + 1]. min), Re );
}
Return re;
}
Public void add (int x)
{
List. Add (X );
If (x> MAX) {max = x ;}
If (x <min) {min = x ;}
}
}
Static ulong ABS (int x, int y)
{
// 3.
Switch (X. compareto (y ))
{
Case-1:
Return (ulong) Y-(ulong) X;
Case 1:
Return (ulong) x-(ulong) y;
}
Return 0ul;
}
Static ulong min (ulong X, ulong y)
{
If (x> Y) {return y ;}
Return X;
}
}
}