[LeetCode] 1. Two Sum

题目链接:传送门

Description

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

Solution

题意:

给定一组数,其中有两个数满足相加之和为给定值,求这两个数的下标

思路:

(1) 暴力 O(\(n^2\))


class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> V;
        for (int i = 0; i < nums.size(); i++)
            for (int j = i + 1; j < nums.size(); j++)
                if (nums[i] + nums[j] == target){
                    V.push_back(i);
                    V.push_back(j);
                    return V;
                }
        return V;
    }
};

(2) 用 map 标记

这里,看到Discuss里面用的是unordered_map,似乎更为合理,因此做了点改动

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        unordered_map<int, int> idx;   // map<int, int> idx;
        for (int i = 0; i < nums.size(); i++) {
            if (idx.count(target - nums[i]) > 0) {
                res.push_back(idx[target - nums[i]]);
                res.push_back(i);
            }
            idx[nums[i]] = i;
        }
        return res;
};
posted @ 2018-02-12 23:45  酒晓语令  阅读(170)  评论(0编辑  收藏  举报