Flashcards
Sum of Two Values
Cards in this deck (2)
- 1Given an array of integers and a value, determine if there are any two integers in the array which sum equal to the given value.// find_sum_of_two function return true if
// there are two values in array who
// sum to value and returns false otherwise
static boolean find_sum_of_two(int[] A, int val) {
Set found_values = new HashSet();
for (int a : A) {
if (found_values.contains(val - a)) {
return true;
}
found_values.add(a);
}
return false;
} - 2Using sorted arrays// find_sum_of_two_2 function return true if
// there are two values in array who
// sum to value and returns false otherwise
// this solution works only if data is sorted.
// does not require any extra memory.
static boolean find_sum_of_two_2(int[] A, int val) {
for (int i = 0, j = A.length - 1; i < j;) {
int sum = A[i] + A[j];
if (sum == val) {
return true;
}
if (sum < val) {
++i;
} else {
--j;
}
}
return false;
}
Information
- Description
- Flashcards on Sum of Two Values, created by Suhas S on 12/02/2018.
- Created by
- Suhas S
- Views
- 7
- Rating