1. Two Sum

xiaoxiao2021-02-28  108

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

思路:用一个hash表存储每个元素及其相应的index,并在数组中进行循环查找

vector<int> twoSum(vector<int>& nums, int target) { if (nums.size() <= 1)return vector<int>{}; unordered_map<int, int> res; vector<int> idx; for (int i = 0; i < nums.size(); i++)res[nums[i]] = i; for (int i = 0; i < nums.size(); i++){ int tmp = target - nums[i]; if (res.find(tmp) != res.end() && res[tmp] > i){ idx.push_back(i), idx.push_back(res[tmp]); return idx; } } return idx; }
转载请注明原文地址: https://www.6miu.com/read-60495.html

最新回复(0)