LeetCode - 1. Two Sum(8ms)
程序员文章站
2023-03-27 17:35:58
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 ex ......
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].
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int n = nums.size(); map<int, int> m; for(int i=0; i<n; i++) { int temp = target - nums[i]; map<int, int>::iterator it = m.find(temp); if(it != m.end()) { return vector<int> {it->second, i}; } m[nums[i]] = i; } } };
上一篇: 双11期间如何快速做好内容营销合作
下一篇: 13函数式编程&Stream流
推荐阅读
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST
-
LeetCode - 1. Two Sum(8ms)
-
LeetCode_#1_两数之和 Two Sum_C++题解
-
LeetCode(62)-Two Sum
-
LeetCode:Two Sum浅析
-
[LeetCode] 1. Two Sum 两数之和
-
【leetcode】#1 Two Sum【Hash】【Easy】
-
LeetCode 1 Two Sum (hash)
-
[leetcode]1. Two Sum
-
1. Two Sum:关于引用和hash table的思考