O(n log(n)) algorithm that checks if sum of 2 numbers in a int[] = given number

前端 未结 5 608
心在旅途
心在旅途 2021-01-03 11:24

I am supposed to create a O(n log(n)) algorithm that checks if sum of 2 numbers in a int[] == given number.

eg. Given [1,4,7,2,3,4] there will be a sum

5条回答
  •  萌比男神i
    2021-01-03 12:09

    Similar to @user384706, however you can do this with in O(n).

    What they say is the following: S=[1,4,7,2,3,4]

    Add these to a HashSet, ideally TIntHashSet (but the time complexity is the same)

    int total = 9;
    Integer[] S = {1, 4, 7, 2, 3, 4, 6};
    Set set = new HashSet(Arrays.asList(S));
    for (int i : set)
        if (set.contains(total - i))
            System.out.println(i + " + " + (total - i) + " = " + total);
    

    prints

    2 + 7 = 9
    3 + 6 = 9
    6 + 3 = 9
    7 + 2 = 9
    

提交回复
热议问题