Leetcode 1 - Two Sum

来源:互联网 发布:快易宝软件下载 编辑:程序博客网 时间:2024/05/21 06:56

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

1 - 空间换时间。
2 - 第一次遍历数组,将每个元素num[i]及其对应下标i存入哈希表。
3 - 第二次遍历数组,对每个元素num[i],求出second = target - nums[i],并验证哈希表中是否存在second。若存在,则将其下标加入结果集。

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> result;        unordered_map<int,int> map;        //将每个元素及其下标存入哈希表        for(int i=0;i<nums.size();i++){            map[nums[i]] = i;        }        //查找哈希表        for(int i=0;i<nums.size();i++){            const int second = target - nums[i];            if(map.find(second)!=map.end() && map[second]>i){                result.push_back(i+1);                result.push_back(map[second]+1);                return result;            }        }    }};
0 0
原创粉丝点击