find pair of numbers in array that add to given sum

前端 未结 19 2166
萌比男神i
萌比男神i 2020-11-30 20:17

Question: Given an unsorted array of positive integers, is it possible to find a pair of integers from that array that sum up to a given sum?

Constraints: This shou

19条回答
  •  情歌与酒
    2020-11-30 20:45

    In java, this is depends on max number in array. it returns an int[] having the indexes of two elements. it is O(N).

      public static int[] twoSum(final int[] nums, int target) {
        int[] r = new int[2];
        r[0] = -1;
        r[1] = -1;
        int[] vIndex = new int[0Xffff];
        for (int i = 0; i < nums.length; i++) {
            int delta = 0Xfff;
            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;
    }
    

提交回复
热议问题