【LeetCode 1 : Two Sum】
来源:互联网 发布:台湾淘宝跟大陆一样吗 编辑:程序博客网 时间:2024/06/15 12:11
Description:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
// 方法一:class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { map<int, int> m; int sz = nums.size(); for(int i = 0; i < sz; ++i) { map<int, int>::iterator p = m.find(target - nums[i]); if(p != m.end()) { vector<int> ret; ret.push_back(p->second+1); ret.push_back(i+1); return ret; } m[nums[i]] = i; } }};
// 方法二:class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> mapping; vector<int> result; for(int i = 0; i < nums.size(); i++) { mapping[nums[i]] = i; } for(int i = 0; i < nums.size(); i++) { const int gap = target - nums[i]; if(mapping.find(gap) != mapping.end()) { result.push_back(i+1); result.push_back(mapping[gap] + 1); break; } } return result; }};
小结:
使用Hash表,进行存储相应的键值对,这种方法会常用;
0 0
- LeetCode 1 - Two Sum
- leetcode 1 Two Sum
- Leetcode【1】:Two Sum
- [leetcode 1] Two Sum
- 【leetcode-1】Two Sum
- [leetcode 1] Two Sum
- [Leetcode] 1 - Two Sum
- LeetCode (1) Two Sum
- LeetCode 1:《Two Sum》
- LeetCode | #1 Two Sum
- leetcode-1 Two Sum
- Two Sum | LeetCode(1)
- [Leetcode]1Two Sum
- leetcode 1 Two Sum
- leetcode #1 Two Sum
- leetcode 1:Two Sum
- LeetCode 1 Two Sum
- leetcode #1 two sum
- linux删除历史操作命令
- Spring--JdbcTemplate
- Knockout Subscription
- Hotspot虚拟机
- html 表格小demo
- 【LeetCode 1 : Two Sum】
- JSP更改地址栏图标的方法
- LTE学习:PHICH
- 浅析C#中的索引器
- openwrt简单ipk生成及Makefile解释
- 浅谈C++中的重载、覆盖(重写)、隐藏
- SimpleDateFormat使用详解
- 摄像头倒置怎么办?
- 英文论文中“such as, for example, e.g., i.e., etc., et al. ”的用法分析