This is an interview question: with integer xand take into account sorted array a[] of N distinct integersa linear-time algorithmto determine if there are two different indices i and j such that a[i] + a[j] == x. Additional storage is not allowed. I implemented this in Java. but my current work time O(nlogn)is because I'm doing binarySearchon each iteration. so it’s not strict linear. I am wondering if there is any for this problem linear time solution. If so, some pointers to it may be useful.
Thank.
public class SumArrayIndex {
public static void main(String[] args){
int[] arr={1,2,3,4,5,6,7,8,9,10};
sumSortedArray(arr, 4);
System.out.println();
sumSortedArray(arr, 19);
System.out.println();
sumSortedArray(arr, 100);
}
public static void sumSortedArray(int[] arr, int sum){
for (int i=0;i<arr.length;i++){
int temp=Arrays.binarySearch(arr, sum-arr[i]);
if (temp>0 && temp!=i){
System.out.printf("The two indices are %s and %s%n ",i,temp);
return;
}
}
System.out.printf("The sum:%s cannot be formed with given array:%s",sum,Arrays.toString(arr));
}
}
source
share