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

用一个 map 把出现的数存起来,key 是目标与该数的差值,value 是该数的编号。假如当前数在 map 中能找到,那么说明找到了一对数的和等于目标,返回两个下标即可。

时间复杂度:O(n)O(n)

C++

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> m;
        int sz = nums.size();
        for(int i=0; i < sz; i++){
            if(m.find(nums[i])==m.end())
                m[target-nums[i]] = i;
            else return vector<int>{m[nums[i]],i};
        }
        return vector<int>{};
    }
};

Java

class Solution {
    public int[] twoSum(int[] a, int t) {
        Map<Integer,Integer> m=new HashMap<Integer,Integer>();
        int[] res=new int[2];
        int n=a.length;
        for(int i=0;i<n;i++){
            if(m.containsKey(a[i])){
                res[0]=i;
                res[1]=m.get(a[i]);
                return res;
            } else m.put(t-a[i],i);
        }
        return res;
    }
}

Python

class Solution:
    def twoSum(self, a: List[int], t: int) -> List[int]:
        m,n = {},len(a)
        for i in range(n):
            if a[i] in m:
                return [m[a[i]],i]
            else:
                m[t-a[i]]=i
        return []

Go

func twoSum(a []int, t int) []int {
    m:=make(map[int]int)
    for i,v := range a {
        j,ok:=m[v]
        if ok {
            return []int{j,i}
        } else {
            m[t-v]=i
        }
    }
    return []int{}
    
}
posted @ 2020-05-02 22:00  winechord  阅读(112)  评论(0编辑  收藏  举报