import java.util.Arrays;
public class FindSum {
public static void main(String[] args) {
int[] arr = {6,1,2,3,7,12,10,10};
int target = 20;
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
int left = 0,right = arr.length - 1;
if (FindSum.binarySearch(arr, target, left, right)) {
System.out.println("Found!");
} else {
System.out.println("Not Found :(");
}
}
public static boolean binarySearch(int[] arr, int target,int left, int right){
int currSum = arr[left] + arr[right];
while(right > left){
if(currSum == target)
{
return true;
}
else if(currSum > target)
{
if(right > left)
return binarySearch(arr,target,left,right-1);
}
else{
if(left < right)
return binarySearch(arr,target,left+1,right);
}
}
return false;
}
}
==============================================================================================
public int[] twoSum(int[] numbers, int target) {
int[] results=new int[2];
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
for(int i=0; i<numbers.length;i++)
{
hm.put(numbers[i],i);
}
for (int i=0;i<numbers.length;i++)
{
int key= target - numbers [i];
if(hm.containsKey(key))
{
int indx2=hm.get(key);
if(i<indx2)
{
results[0]=i+1;
results[1]=indx2+1;
}
}
}
return results;
}