leecode第一天

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the sameelement twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

一句话,就是找到数组中两个元素的位置,使得该两个元素的和为target所指定的值。

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();//将数组中的值放入到map的key中,目的是为了可以使用map.containskey()获得key值,前提是数组中没有相同的元素。
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];//获得另外一个元素的值
        if (map.containsKey(complement) && map.get(complement) != i) {//保证不使用相同的元素两次
            return new int[] { i, map.get(complement) };
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

 暴力求解的方法。

public int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[j] == target - nums[i]) {
                return new int[] { i, j };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

猜你喜欢

转载自blog.csdn.net/weixin_39912556/article/details/82807795