LeetCode 1. Two Sum
来源:互联网 发布:营业部买卖数据 编辑:程序博客网 时间:2024/04/30 15:29
题目:
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].
思路:
定义一个返回结果的vector,定义一个unordered_map,unordered_map比map快,用来记录nums中每个数对应的index。如果mymap中有值与target-nums[i]相等,就将当前的值和与当前值相加等于target相等的那个值的index放到result里。因为index要按顺序输出,所以要排序,然后返回结果;如果不相等,则只将当前值和对应的index放到mymap里。最后如果result中没有值,其实就是返回了一个空vector。
代码:
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> result;//返回结果的vector size_t len = nums.size();//计算nums的长度 unordered_map<int, int> mymap;//unordered_map比map快,用来记录nums中每个数对应的index for (size_t i = 0; i < len; ++i){ if (mymap.count(target - nums[i])){//如果mymap中有值与target-nums[i]相等 result.push_back(i);//就将当前的值和与当前值相加等于target相等的那个值的index放到result里 result.push_back(mymap[target - nums[i]]); sort(result.begin(), result.end());//index要按顺序输出,所以排序 return result;//返回结果 } mymap[nums[i]] = i;//如果不相等,则只将当前值和对应的index放到mymap里 } return result;//如果没有找到,其实是返回空vector }};
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
- 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
- Linux下解决/boot分区不足
- EasyUI之验证框validatebox
- linux如何配置文件系统分区
- Servlet机制原理2
- 第五天2017/04/06(下午1:C、C++混合编程 与 #ifdef __cplusplus extern "C"{ })
- LeetCode 1. Two Sum
- Tomcat报错
- Hibernate学习笔记3--映射关联关系
- IT404过关游戏WP
- The method getContextPath() from the type HttpServletRequest refers to the missing type
- Hexo NexT 主题下 blockquote 文本内容超出不自动换行解决方式
- 背包九讲
- 2017 蓝桥杯JavaB组省赛 日期问题
- LeetCode 111. Minimum Depth of Binary Tree