Friday, February 7, 2014

Find out if any two numbers that array add up to a target

write a function that finds out if any two numbers within that array add up to a target
Target: 17
array: 2, 23, 21, 3, 5, 7, 10, 12 ,8, 11
sort the array: 2, 3, 5, 7, 8, 10, 11, 12, 21, 23
index start and the end, calculate the sum;
if the sum < target, increment the start,  sum > target, decrement  the end;
public void findTarget(int[] array, int target) {
    int start = 0;
    int end = array.length - 1;
    //Complexity of sort -> O(nlogn)
    java.util.Arrays.sort(array);
    while (start < end) {
        if (array[start] + array[end] == target) {
            System.out.println(array[start] + array[end]);
            return;
        } else if (array[start] + array[end] < target) {
            start++;
        } else {
            end--;
        }
    }
}

No comments:

Post a Comment