Example:
Input : {1,2,4,5,3}, number = 8
Output : 5, 3 (because 5+3 = 8(given number))
Implementation
Method 1:
public static void findSum3(int []a, int sum){
if(array == null || array.length == 0)
return ;
for(int i = 0; i < a.length; i++){
for(int j = i+1; j < a.length; j++){
if(a[i] + a[j] == sum){
System.out.println(a[i] + " "+a[j]);
break;
}
}
}
}
Time Complexity : O(N^2)
Space Complexity : O(1)
Method 2:
public static void findSum(int []a, int sum){
if(array == null || array.length == 0)
return ;
Hashtable h = new Hashtable();
for(int i = 0; i < a.length; i++){
//if sum-a[i] is in hashtable then we already found the pair.
if(h.containsKey(sum - a[i])){
System.out.println(a[i] +" "+(sum - a[i]));
}
else{ //put the element of array into hashtable, if it doesnot have it.
h.put(a[i], true);
}
}
}
Time Complexity : O(N)
Space Complexity : O(N)
Method 3:
public static void findSum2(int []a, int sum){
if(array == null || array.length == 0)
return ;
//sort the array
Arrays.sort(a);
int first = 0;
int last = a.length - 1; //last element
while(first < last){
int s = a[first] + a[last]; //sum of first and last element of array
if(s == sum){
System.out.println(a[first] +" "+ a[last]);
first++;
last--;
}else{
if(s < sum)
first++;
else
last--;
}
}
}
Time Complexity : O(NlogN)
Space Complexity: O(1)
Input : {1,2,4,5,3}, number = 8
Output : 5, 3 (because 5+3 = 8(given number))
Implementation
Method 1:
public static void findSum3(int []a, int sum){
if(array == null || array.length == 0)
return ;
for(int i = 0; i < a.length; i++){
for(int j = i+1; j < a.length; j++){
if(a[i] + a[j] == sum){
System.out.println(a[i] + " "+a[j]);
break;
}
}
}
}
Time Complexity : O(N^2)
Space Complexity : O(1)
Method 2:
public static void findSum(int []a, int sum){
if(array == null || array.length == 0)
return ;
Hashtable h = new Hashtable();
for(int i = 0; i < a.length; i++){
//if sum-a[i] is in hashtable then we already found the pair.
if(h.containsKey(sum - a[i])){
System.out.println(a[i] +" "+(sum - a[i]));
}
else{ //put the element of array into hashtable, if it doesnot have it.
h.put(a[i], true);
}
}
}
Time Complexity : O(N)
Space Complexity : O(N)
Method 3:
public static void findSum2(int []a, int sum){
if(array == null || array.length == 0)
return ;
//sort the array
Arrays.sort(a);
int first = 0;
int last = a.length - 1; //last element
while(first < last){
int s = a[first] + a[last]; //sum of first and last element of array
if(s == sum){
System.out.println(a[first] +" "+ a[last]);
first++;
last--;
}else{
if(s < sum)
first++;
else
last--;
}
}
}
Time Complexity : O(NlogN)
Space Complexity: O(1)