首页 > 其他 > 详细

[Algo] Find Pair with Given Sum

时间:2020-04-06 10:00:57      阅读:56      评论:0      收藏:0      [点我收藏+]

Given a list of positive integers nums and an int target, return indices of the two numbers such that they add up to a target - 30.

 

Conditions:

 

  • You will pick exactly 2 numbers.
  • You cannot pick the same element twice.
  • If you have muliple pairs, select the pair with the largest number.

 

Example 1:

 

Input: nums = [1, 10, 25, 35, 60], target = 90
Output: [2, 3]
Explanation:
nums[2] + nums[3] = 25 + 35 = 60 = 90 - 30

 

Example 2:

 

Input: nums = [20, 50, 40, 25, 30, 10], target = 90
Output: [1, 5]
Explanation:
nums[0] + nums[2] = 20 + 40 = 60 = 90 - 30
nums[1] + nums[5] = 50 + 10 = 60 = 90 - 30
You should return the pair with the largest number.

    public static int[] getPairSum(int[] arr, int target) {
        int[] res = new int[]{-1, -1};
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            int num = target - arr[i] - 30;
            if (map.containsKey(num)) {
                int preIndex = map.get(num);
                if (res[0] == -1 && res[1] == -1 || i + preIndex > res[0] + res[1]) {
                    res[0] = map.get(num);
                    res[1] = i;
                }
            } else {
                map.put(arr[i], i);
            }
        }
        return res;
    }

 

 

[Algo] Find Pair with Given Sum

原文:https://www.cnblogs.com/xuanlu/p/12640385.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!