题目描述
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.
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
首先我们可以想到使用brute force,简单粗暴。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { for(int i=0; i < nums.size(); ++i) { for(int j=i+1; j < nums.size(); ++j) { int sum = nums[i] + nums[j]; if(sum == target) { return {i, j}; } } } return {}; } }
可以通过,但是时间复杂度较高,非最优解。
可以在循环之前维护一张map,存储值和对应的Index, 在循环中用target减去循环到的值,看差值是否在map中,并且要满足you may not use the same element twice. 这个条件,因此需要indies[left] != i下面是较优解法
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> indies; for(int i=0; i < nums.size(); ++i) indies[nums[i]] = i; for(int i=0; i < nums.size(); ++i) { int left = target - nums[i]; if(indies.count(left) && indies[left] != i) { return {i, indies[left]}; } } return {}; } };