1. 程式人生 > >演算法---從一個數組(或者集合中)找出和為某個值的下標

演算法---從一個數組(或者集合中)找出和為某個值的下標

    public static int[] twoSum(int[] nums, int target) {
        //因為你要找到這兩個相加等於目標數,因此我認為你至少要遍歷一次
        Map hashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (hashMap.containsKey(complement)) {
                return new int[]{hashMap.get(complement), i};
            }
            hashMap.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }