Find a pair of elements from an array whose sum equals a given number

后端 未结 30 1493
暗喜
暗喜 2020-11-22 10:14

Given array of n integers and given a number X, find all the unique pairs of elements (a,b), whose summation is equal to X.

The following is my solution, it is O(nLo

30条回答
  •  半阙折子戏
    2020-11-22 10:58

     public static int[] f (final int[] nums, int target) {
        int[] r = new int[2];
        r[0] = -1;
        r[1] = -1;
        int[] vIndex = new int[0Xfff];
        for (int i = 0; i < nums.length; i++) {
            int delta = 0Xff;
            int gapIndex = target - nums[i] + delta;
            if (vIndex[gapIndex] != 0) {
                r[0] = vIndex[gapIndex];
                r[1] = i + 1;
                return r;
            } else {
                vIndex[nums[i] + delta] = i + 1;
            }
        }
        return r;
    }
    

提交回复
热议问题