How can I find two elements in an array that sum to k

前端 未结 4 1206
不知归路
不知归路 2020-12-18 14:26

Suppose you are given an array of unsorted integers as

A = {3,4,5,1,4,2}

Input : 6 Output : {5,1}, {4,2}

4条回答
  •  盖世英雄少女心
    2020-12-18 15:10

    If the numbers stored in the input array are only positive then I'd create another array K of k+1 ArrayList elements. Where k is the number you need them to add up to. Only two numbers less than k can add up to k (assuming we deal with positive ints} or in special case {0,k}. Then I would iterate through all elements of input array and for each int m that is less or equal to k I'd take its index and add that index to the array of ArrayList K at index m. Then I would iterate through first half of the array K and for each index i that has some ints stored in it I would find complementary index [k-i] and see if there are any values in it. If there are then those are your pairs. And btw this is O(n).

    public static void findElemtsThatSumTo( int data[], int k){
        List arrayK[]= new List[k+1];
        for(int i=0; i();
    
        for(int i=0; i

提交回复
热议问题