LeetCode之Tow Sum

Problem:

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 same element twice.

给你一个整数数组,返回两个数组元素的下标,这两个数组元素相加得到一个特殊的数字target。

你可以假定每次输入只有一个正确答案,但你不能使用同一个元素两次以上。

Solution

--1--

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");
}
双重循环

new Int[] = {} --- Java数组当对象new出来

IllegalArgumentException --- 参数异常

--2--

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    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");
}
借助HashMap,单循环

map.containKey --- 判断map是否含有该值

posted @ 2020-01-03 10:47  喜欢数学也爱代码  阅读(96)  评论(0编辑  收藏  举报