Two Sum - LeetCode

eclaircpeclaircp
1 min read

Problem Link

C++ Code

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {

        map<int, int> hashMap;

        vector<int> ans;

        for(int i=0; i<nums.size(); i++) {

            int num = nums[i];

            if(hashMap.find(target-num)!=hashMap.end()) {
                ans.insert(ans.begin(), {i, hashMap[target-num]});
            }

            hashMap[num] = i;
        }

        return ans;
    }
};

TypeScript Code

function twoSum(nums: number[], target: number): number[] {

    let hashMap = new Map<number, number>();

    let ans: Array<number> = [];

    for(let i=0; i<nums.length; i++) {

        let num: number = nums[i];

        if(hashMap.has(target-num)) {
            ans.push(i, hashMap.get(target-num));
            break;
        }

        hashMap.set(num, i);
    }

    return ans;
};

Go Code

func twoSum(nums []int, target int) []int {

    hashMap := make(map[int] int)

    var ans []int

    for idx, num := range nums {
        if existingIdx, ok := hashMap[target-num]; ok {
            ans = append(ans, idx, existingIdx)
            break
        }

        hashMap[num] = idx
    }

    return ans
}
0
Subscribe to my newsletter

Read articles from eclaircp directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

eclaircp
eclaircp