1. Two Sum

来源:互联网 发布:广州seo搜索引擎优化 编辑:程序博客网 时间:2024/06/11 20:05

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.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        unordered_map<int,int> hash;        vector<int> newsum;        int i,j;        for(i=0;i<nums.size();i++)        {            if(hash.find(target-nums[i])!=hash.end())            {                newsum.push_back(hash[target-nums[i]]);                newsum.push_back(i);            }            else            {                hash[nums[i]]=i;            }        }        return newsum;    }};

思路:就是遍历一遍所有数据,用target数据减去遍历的数据,然后假如减去后得到的数据是在哈希表里的,那么就说明得到了我们想要的东西。假如没有在哈希表中找到,那么就把这个数放入哈希表里。

0 0
原创粉丝点击