美文网首页
LeetCode - Two Sum - Java / Pyth

LeetCode - Two Sum - Java / Pyth

作者: 音符纸飞机 | 来源:发表于2018-10-11 10:21 被阅读7次

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].

Java

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> lookup= new HashMap<>();
        for (int i = 0; i < nums.length; ++i){
            int diff  = target - nums[i];
            if(lookup.get(diff) != null){
                return new int[]{lookup.get(diff), i};
            } else {
                lookup.put(nums[i], i);
            }
        }
        return null;
    }
}

Python

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        lookup = {}
        for idx, num in enumerate(nums):
            if target - num in lookup:
                return [lookup[target - num], idx]
            lookup[num] = idx
        
        

相关文章

网友评论

      本文标题:LeetCode - Two Sum - Java / Pyth

      本文链接:https://www.haomeiwen.com/subject/adnvaftx.html