We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Running brute force algorithm in C# for a lab. Test case 4 has timeout error. My algorithm is O(n^2) [as far as I know]
staticint[]closestNumbers(int[]arr){intsmallestDistance=Int32.MaxValue;intdistance;List<int>result=newList<int>();sw=Stopwatch.StartNew();Array.Sort(arr);for(inti=0;i<arr.Length;i++){for(intj=i+1;j<arr.Length;j++){distance=Math.Abs(arr[i]-arr[j]);if(distance<smallestDistance){smallestDistance=distance;result.Clear();result.Add(arr[i]);result.Add(arr[j]);}elseif(distance==smallestDistance){result.Add(arr[i]);result.Add(arr[j]);}}}result.Sort();sw.Stop();WriteLine("Time taken in brute force: "+(sw.ElapsedMilliseconds/1000.0));returnresult.ToArray();}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Closest Numbers
You are viewing a single comment's thread. Return to all comments →
Running brute force algorithm in C# for a lab. Test case 4 has timeout error. My algorithm is O(n^2) [as far as I know]