Leetcode #1 Two Sum

Posted by blueskyson on February 7, 2021

Description

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Solution 1

暴力法

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    int *ret = (int*)malloc(sizeof(int) * 2);
    for (int i = 0; i < numsSize; i++) {
        for (int j = i + 1; j < numsSize; j++) {
            if (nums[i] + nums[j] == target) {
                ret[0] = i;
                ret[1] = j;
            }
        }
    }
    *returnSize = 2;
    return ret;
}

Runtime: 24 ms, faster than 8.34% of C online submissions for Two Sum.

Memory Usage: 5.9 MB, less than 64.44% of C online submissions for Two Sum.

go

1
2
3
4
5
6
7
8
9
10
11
func twoSum(nums []int, target int) []int {
    max := len(nums);
    for i := 0; i < max; i++ {
        for j := i + 1; j < max; j++ {
            if (nums[i] + nums[j] == target) {
                return []int{i, j}
            }
        }
    }
    return []int{}
}

Runtime 31 ms Beats 35.12%

Memory 3.5 MB Beats 93.42%

Solution 2

map

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ret;
        map<int, int> m;
        map<int, int>::iterator iter;
        
        for (int i = 0; i < nums.size(); i++) {
            iter = m.find(target - nums[i]);
            if (iter != m.end()) {
                ret.push_back(i);
                ret.push_back(iter->second);
                break;
            }
            m.insert(pair<int, int>(nums[i], i));
        }
        return ret;
    }
};

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Two Sum.

Memory Usage: 9 MB, less than 78.23% of C++ online submissions for Two Sum.

go

1
2
3
4
5
6
7
8
9
10
11
12
13
func twoSum(nums []int, target int) []int {
    nums_map := make(map[int]int)
    max := len(nums);

    for i := 0; i < max; i++ {
        val, ok := nums_map[target - nums[i]]
        if ok {
            return []int{val, i}
        }
        nums_map[nums[i]] = i
    }
    return []int{}
}

Runtime 8 ms Beats 87.41%

Memory 4.2 MB Beats 53.53%