checking if 2 numbers of array add up to I

后端 未结 15 2687
日久生厌
日久生厌 2020-12-15 01:13

I saw a interview question as follows: Give an unsorted array of integers A and and an integer I, find out if any two members of A add up to I.

any clues?

ti

15条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 02:00

    public static boolean findSum2(int[] a, int sum) {
            if (a.length == 0) {
                return false;
            }
            Arrays.sort(a);
    
    
            int i = 0;
            int j = a.length - 1;
            while (i < j) {
                int tmp = a[i] + a[j];
                if (tmp == sum) {
                    System.out.println(a[i] + "+" + a[j] + "=" + sum);
                    return true;
                } else if (tmp > sum) {
                    j--;
                } else {
                    i++;
                }
            }
            return false;
    }
    

提交回复
热议问题