Leetcode 1 - Two Sum

Problem Description

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) {
        HashMap<Integer, Integer> map = new HashMap<>();
        
        for (int i = 0; i < nums.length; i++) {
            if(map.containsKey(target - nums[i])) {
                return new int[] {map.get(target - nums[i]), i};
            } else {
                map.put(nums[i], i);
            }
        }
        
        return new int[]{0, 0};
    }
}

Python:

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

Go:

func twoSum(nums []int, target int) []int {
    m := make(map[int]int)
    
    for i := 0; i < len(nums); i++ {
        if v, ok := m[nums[i]]; ok {
            return [] int { v, i }
        } else {
            m[target - nums[i]] = i
        }
    }
    
    return []int{0, 0}
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,159评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,469评论 0 23
  • 先从Easy开始吧,毕竟菜。 原题: Given an array of integers, return ind...
    littlefogcat阅读 1,761评论 0 0
  • 灯光倾泻 操场上传来悠悠扬扬的歌声 刚出图书馆的大门 便撞见了嘶嘶的北风 心中有一股欲说还休的冲动 又拾起了好...
    顾姜生阅读 897评论 0 0
  • 今天是2016年的最后一天了,昨天晚上回家的路上看着车辆来来往往一直在想这一年来到我到底收获失去了什么? 16年3...
    太阳小草就是花阅读 1,404评论 0 0