LeetCode-Two Sum

来源:互联网 发布:wine for mac 编辑:程序博客网 时间:2024/06/05 10:03

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 thesame element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
C++ solution:
class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        unordered_map<int, int> a;        vector<int> result;        for (int i = 0; i < nums.size(); i++) {            a[nums[i]] = i;        }        for (int i = 0; i < nums.size(); i++) {            int t = target - nums[i];            if (a.count(t) && a[t] != i) {                result.push_back(i);                result.push_back(a[t]);                break;            }        }        return result;    }};
题目给出一组数组和一个目标,要求在数组中找到两个不同元素的和等于该目标,理解为:nums[a]+nums[b]=target,结果返回数组下标a,b。当选定nums[a],可知nums[b]=target-nums[a],只需查找数组中是否含有该数值。通过unprdered_map确认nums[b]和 i 值。

原创粉丝点击