LeetCode - Two Sum - Java / Python

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
        
        
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容