When I was asked to write a method that would check if any pair in array list is equal to given value, I came up with this:
import java.util.ArrayList;
public class FindWhetherTwoInArrEqual {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(10); arr.add(12);
arr.add(18); arr.add(10);
arr.add(8); arr.add(12);
arr.add(33); arr.add(28);
arr.add(2); arr.add(20);
findWhetherTwoInArraySumToValue(arr, 30);
}
public static boolean findWhetherTwoInArraySumToValue(ArrayList<Integer> array, int value)
{
for(int i = 0; i < array.size(); ++i)
for(int j=i+1; j < array.size(); ++j)
if(array.get(i) + array.get(j) == value)
System.out.println(array.get(i) +" + "+ array.get(j) + " = " + value);
return false;
}
}
Result:
10 + 20 = 30
12 + 18 = 30
18 + 12 = 30
10 + 20 = 30
28 + 2 = 30
The time complexity is O(n).
Is there more efficient way of doing this?