I need to print the least difference between any two elements of an int array.
each element of array A is less than equal to its length.
1 <= A[i] <= A.length;
I have tried this below given approach in Java - But this takes more than 1 second to find results when array size is given ~10^5.
I think it may be a naive approach. Is there any way i can optimize it further?
Can it be done in O(n) time complexity?
static int findResult(int[] arr)
{
int max = Integer.MAX_VALUE;
HashSet<Integer> hs = new HashSet<Integer>();
for(int obj : arr)
{
hs.add(obj);
}
if(hs.size()==1 )
{
return 0; // if all elements are same
}
for(int i=0; i<arr.length; i++)
{
for(int j=i+1; j<arr.length; j++)
{
int value = Math.abs(a[i]-a[j]);
if(value<max)
{
max = value;
}
}
}
return max; // returns the smallest positive difference
}