Two Sum

The problem is to find the indices of two numbers in an array that add up to a target. There is always a solution, and you can't use the same element twice.

Problem

Given an array of integers, return the 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].

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> map;
    vector<int> result;
    for (int i = 0; i < nums.size(); i++) {
        if (map.find(target - nums[i]) != map.end()) {
            result.push_back(map[target - nums[i]]);
            result.push_back(i);
            return result;
        }
        map[nums[i]] = i;
    }
    return result;
}

int main() {
    vector<int> nums = {2, 7, 11, 15};
    int target = 9;
    vector<int> result = twoSum(nums, target);
    for (int i = 0; i < result.size(); i++) {
        cout << result[i] << " ";
    }
    cout << end l;
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The approach is to use a hash map to store the elements of the array and their corresponding indices. Then, for each element in the array, the candidate checks if the hash map contains an element that is equal to the target minus the current element. If such an element is found, then the candidate returns the indices of the two elements. Otherwise, the candidate adds the current element to the hash map.

Evaluated at: 2022-11-20 02:16:13