How to Reduce the time limit of my code?


#1

public class Solution {
public int solve(ArrayList a) {
Collections.sort(a);
int count=0;
for(int i=0;i<a.size();i++)
{int sum=0;
for(int j=i;j<a.size();j++)
{
if(a.get(i)<a.get(j))
{
sum++;
if(sum>a.get(i))
break;
}
}
if(sum==a.get(i))
count++;
}
if(count==0)
return -1;
return 1;
}
}


#2

No need to do in O(n^2). It can be done in O(nLogn) easily.