LeetCode1 Two Sum

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.

Example:

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

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

go语言解法

func twoSum(nums []int, target int) []int {
    //使用make函数来创建切片(动态数组)
    //此处的m数组是键值对
    m := make(map[int]int)
    
    //for 循环的 range 格式可以对 slice、map、数组、字符串等进行迭代循环
    for i, n := range nums {
        //_表示忽略该变量,此处忽略第一个变量
        _, prs := m[n]
        if prs {
            return []int{m[n], i}
        } else {
            m[target-n] = i
        }
    }
    //nil表示空值
    return nil
}

java解法

public int[] twoSum(int[] nums, int target) {
        //用map键值对存元素和元素的下标
        Map map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            //如果map中包含要找的值
            if (map.containsKey(complement)) {
                //生成新的数组,其中map.get(complement)是获取该元素的下标
                return new int[] {map.get(complement), i};
            }
            //如果没找到,就把该元素放入到map中
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }

你可能感兴趣的:(LeetCode1 Two Sum)