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

前端 未结 4 1205
不知归路
不知归路 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:05

    As with your other question, O(log n) is impossible, since you have to examine the entire array. But O(n) is more or less possible.

    If your range of possible integers is relatively small — that is, if it's within a constant factor of n — then you can write:

    final boolean[] seen = new boolean[max - min + 1];
    for(final int a : A)
    {
        if(seen[input - a - min])
            System.out.println("{" + (input - a) + "," + a + "}");
        seen[a - min] = true;
    }
    

    If not, you can do the same thing, but using a HashSet instead of an array:

    final Set seen = new HashSet();
    for(final int a : A)
    {
        if(seen.contains(input - a))
            System.out.println("{" + (input - a) + "," + a + "}");
        seen.add(a);
    }
    

    but that will not have guaranteed O(n) time.

提交回复
热议问题