leetcode-1.two sum
2018-01-27 17:56
363 查看
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:
思路:找容器vector中找到两个数使得A+B=Target,可以建立无序容器unordered_map,在unordered_map依次查找vector中的每个元素i,若没有找到,则在unordered_map中建立key为Target-i ,value为i的index的元素,直到在unordered_map找到i。
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].
思路:找容器vector中找到两个数使得A+B=Target,可以建立无序容器unordered_map,在unordered_map依次查找vector中的每个元素i,若没有找到,则在unordered_map中建立key为Target-i ,value为i的index的元素,直到在unordered_map找到i。
#include <vector> #include<iostream> #include <unordered_map> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { std::unordered_map<int, int> record; for (int i = 0; i != nums.size(); ++i) { auto found = record.find(nums[i]); if (found != record.end()) return { found->second, i }; record.emplace(target - nums[i], i); } return { -1, -1 }; } }; int main() { vector<int> vec = { 1, 4 ,6 ,7, 8, 13 }; int tar = 12; Solution solu; vector<int> p=solu.twoSum(vec, tar); for (auto &num : p) cout << num << endl; system("pause"); return 0; }
相关文章推荐
- leetcode刷题笔记-two sum
- LeetCode:Algorith1 —Two Sum
- LeetCode --> Two Sum
- LeetCode|Two Sum-java
- Leetcode 1:two sum
- LeetCode笔记-A1-Two Sum
- [LeetCode]--1. Two Sum
- [leetcode]1.Two Sum
- LeetCode Two Sum
- LeetCode 1.Two Sum
- LeetCode 1 Two Sum
- LeetCode-Two Sum
- LeetCode - Two Sum
- 【Leetcode】Two Sum
- LeetCode || Two Sum
- [Leetcode] Two Sum
- LeetCode - Two Sum
- 【LeetCode】Two Sum
- LeetCode 1.Two Sum (Python)
- [LeetCode] 1. Two Sum