jeudi 9 avril 2020

Closest Numbers Hacker rank - Two test cases failing while using tuples

Below is my code that I have written. It sucessfully passes 4 test cases but it fails on two test cases. Its a well known problem in hackerrank but I am still not able to work out why my code fails in those two test cases. Please help me resolve this issue. Link to the question - https://www.hackerrank.com/challenges/closest-numbers/problem

#include <bits/stdc++.h>
using namespace std;


typedef tuple<int,int,int> tt;

bool sortbyasec(const tuple <int,int,int> &t1,const tuple <int,int,int> &t2)
{    
      return ((get<2>(t1) < get<2>(t2)) );    
}

int main()
{
    int TC;
    cin>>TC;
    vector <int> arr;

    for(int i = 0; i<TC; i++)
    {
       long long int x;
       cin>>x;

       arr.push_back(x);
   }


sort(arr.begin(),arr.end());
vector<tt> t1;
int diff;


for (size_t i = 0; i<arr.size()-1;i++)
{

    diff = abs(arr[i] - arr[i+1]);
    t1.push_back(tt(arr[i],arr[i+1],diff));
}
arr.clear();


sort(t1.begin(),t1.end(),sortbyasec);
long int value;
tie(ignore,ignore,value) = t1[0];



for (size_t i = 0; i < t1.size();i++)
{
    if (get<2>(t1[i]) == value)
    {

    cout<<get<0>(t1[i])<<' '<<get<1>(t1[i])<<' ';
    }
}

}

Aucun commentaire:

Enregistrer un commentaire