1. Two sum 两数之和

给出一个整数数组,返回两个加起来等于目标的数字的下标。

假定每个输入只有一个解决方法,每个元素只用一次。

例如:

输入  nums = [2, 7, 11, 15], target = 9

因为  nums[0] + nums[1] = 2 + 7 = 9,

所以 return [0, 1]

python 版本:

def twoSum(nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        buff_dict = {}
        for i, num in enumerate(nums):
            if num in buff_dict:
                return [buff_dict[num], i]
            else:
                buff_dict[target - num] = i

java 版本:

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}

猜你喜欢

转载自blog.csdn.net/romeo12334/article/details/81145452
今日推荐