Leetcode[1]-Two Sum
来源:互联网 发布:淘宝店推广软文 编辑:程序博客网 时间:2024/06/10 12:03
Link:https://leetcode.com/problems/two-sum/
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
分析:
方法一:使用两个for循环,依次比较,不过这个方法在leetcode上超时了
vector<int> twoSum(vector<int>& nums, int target) { vector<int> index(2); int n = nums.size(); for(int i = 0; i < n ; i++) { index[0] = i+1; for(int j = i+1 ; j < n ; j++) { if(nums[i] + nums[j] == target){ index[1] = j+1; return index; } } } return index;}
法二:使用map存储所有的数组值和下标值,然后循环在map中找看能否找到target-nums[i]的map,如果找到了就终止循环,没找到继续找;最后返回index数组;
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> index(2); int n = nums.size(); map<int,int> mapv; for(int i = 0; i < n ; i++) { mapv[nums[i]] = i; } map<int,int>::iterator it; for(int i = 0; i < n; i++) { it = mapv.find(target - nums[i]); if(it != mapv.end() && i!=it->second){ index[0]=min(i+1, it->second + 1); index[1]=max(i+1, it->second + 1); break; } } return index; }};
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
- 在MyEclipse下创建Java Web项目 入门(图文并茂)经典教程
- Google面试题-高楼扔鸡蛋问题
- HDU ACM 1392 Surround the Trees->凸包
- 2015年移动金融应用行业报告
- 歪解Activity生命周期-----初学者彻底理解指南
- Leetcode[1]-Two Sum
- org.tinygroup.htmlparser-Html解析器
- 二分查找
- oracle 数据库 表空间创建 用户创建 用户授权
- org.tinygroup.application-应用启动框架
- Mybatis学习(6)动态sql语句
- centOs6.5_ftp服务器搭建vsftpd
- SVN客户端安装
- org.tinygroup.beancontainer-IOC、AOP框架