一起刷leetcode(1):Two Sum


地址:

https://oj.leetcode.com/problems/two-sum/

题号:

1

题目:

Two Sum

描述:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2.
已邀请:

beta

赞同来自: GaoLiaoLiao c54s888 天天


思路:用哈希
代码:C++(AC)
class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        int n_size = numbers.size();
        unordered_map <int, int> numbers_map;
        for (int i = 0; i < n_size; i++){
            numbers_map[numbers[i]] = i;
        }
        vector <int > result(2);
        for (int i = 0; i < n_size; i++){
            int tmp = target - numbers[i];
            if (numbers_map.find(tmp) != numbers_map.end()){
                if (numbers_map[tmp] != i){
                    result[0] = i + 1;
                    result[1] = numbers_map[tmp] + 1;
                    break;
                }
            }
        }
        return result;
    }
};

要回复问题请先登录注册

收藏七月在线,一起向大牛进阶

ctrl+D或command+D可以快速收藏哦~