[Easy]Two Sum
2017-02-13 21:02
218 查看
Two Sum
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].
Solution
public class Solution { public int[] twoSum(int[] nums, int target) { int result[] = new int[2]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); int index = 0; for (int num:nums) { if (map.containsKey(target - num)) { result[1] = index; result[0] = map.get(target - num); return result; } map.put(num, index++); } return result; } }
Analysis
将求和问题转化为查找问题,查找target-num是否存在相关文章推荐
- RM格式压缩电影软件 Easy RealMedia Producer Full V1.94 下载
- 在IE 浏览器中使用 jquery的fadeIn() 效果 英文字符字体加粗
- jQuery Easy UI中根据第一个下拉框选中的值设置第二个下拉框是否可以编辑
- 比较简单的jquery教程 Easy Ajax with jQuery 中文版全集第1/3页
- Easy RM RMVB to DVD Burner v1.3.8 汉化版 下载 附注册码
- Expandable "Detail" Table Rows
- linux下安装easy_install的方法
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode刷题,没想到这么难搞!
- python在Windows下安装setuptools(easy_install工具)步骤详解
- EasyUI 1.5.1 美化主题 EasyUI 1.5.1 Of Insdep Theme 1.0
- EasyUI 1.5.1 美化主题 EasyUI 1.5.1 Of Insdep Theme 1.0
- 网站前端_EasyUI.基础入门.0004.带你玩转jQuery EasyUI Accordion组件?
- 网站前端_EasyUI.基础入门.0005.使用EasyUI Accordion组件的最佳姿势?
- 归纳整理文件Easy Duplicate Finder2.24 破解版
- DM*** and Easy *** Server with ISAKMP Profiles
- easy ***