LeetCode 167.两数之和 II - 输入有序数组

开始感觉和第1题的解法应该差不多,我在用第1题的方法二时一次性通过,但用方法三的时候就Wrong anwser,我一检查,发现题目条件不一样,第1题是没有重复的元素,而这一题有,Map不可以有重复的键[0,0,3,4],0。用方法三就通不过,但为什么方法二可以呢,我仔细看了下,由于相同Key会刷新Value,当在进行Index = map.get(res)) != j 判断时就会为真。。

package LeetCode167;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LeetCode167 {

    public static void main(String[] args) {
        int[] list;
        list = twoSum(new int[]{0, 0, 3, 4}, 0);
        for (int a : list) {
            System.out.println(a);
        }
    }


    public static int[] twoSum(int[] numbers, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < numbers.length; i++) {
            map.put(numbers[i], i);
        }
        for (int j = 0; j < numbers.length; j++) {
            int res = target - numbers[j];
            int Index;
            if (map.containsKey(res) && (Index = map.get(res)) != j) {
                if (j > Index) return new int[]{Index + 1, j + 1};
                else return new int[]{j + 1, Index + 1};
            }
        }
        throw new IllegalArgumentException("No such numbers");
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41126303/article/details/82414238