(Leetcode) Two Sum
Posted ollie-lin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(Leetcode) Two Sum相关的知识,希望对你有一定的参考价值。
題目:
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.
Code :
1 class Solution 2 { 3 public: 4 vector<int> twoSum(vector<int>& nums, int target) 5 { 6 unordered_map<int, int> mapping; 7 vector<int> result; 8 9 for (int i = 0; i < nums.size(); i++) 10 { 11 mapping[nums[i]] = i; 12 } 13 14 for (int i = 0; i < nums.size(); i++) 15 { 16 const int gap = target - nums[i]; 17 if (mapping.find(gap) != mapping.end() && mapping[gap] > i) 18 { 19 result.push_back(i); 20 result.push_back(mapping[gap]); 21 break; 22 } 23 } 24 25 return result; 26 } 27 };
以上是关于(Leetcode) Two Sum的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode(371) Sum of Two Integers
leetcode371. Sum of Two Integers