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.
public static int lonelyinteger(List<Integer> a) {
// Sort list
Collections.sort(a);
// Return first elem if size is one or second elem doesn't match
int ans=a.get(0);
if(a.size()==1 || a.get(0) != a.get(1))
return ans;
// Iterate through list
for(int i=1;i<a.size()-1;i++) {
// Compare num before and after from index 1 - size-1
if(a.get(i)!= a.get(i-1) && a.get(i)!= a.get(i+1)){
// If unequal return elem
return a.get(i);
}
}
// If each elem has match but last return last
return a.get(a.size()-1);
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Lonely Integer
You are viewing a single comment's thread. Return to all comments →