1. Two Sum
来源:互联网 发布:淘宝 新店扶持 编辑:程序博客网 时间:2024/06/05 23:59
1. 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.
给一个整数数组,给一个数字,返回数组中两个数字的序号,这两个数字加起来等于给定数字。
假设每个输入只有一个确定的解。
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
public class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int len = nums.length; int[] defaultResult ={0,0}; for(int i = 0; i < len; i++){ if(map.get(target-nums[i]) != null){ int[] result = {map.get(target-nums[i]), i}; return result; } map.put(nums[i], i); } return defaultResult; }}new一个HashMap,得到数组长度,初始化结果。
给定数字减数组中数字,其结果没在map中,就加入map。有就返回两个数字的序号。
HashMap中是key-value,对此题目,数字作为key,序号为value
0 0
- 1. Two Sum && 167. Two Sum II
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1. Two Sum
- 1. Two Sum Ruby
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1.Two Sum
- 一些思考方式——从continue按钮的实现暴露的设计问题
- 三大简单排序
- IOS 内存管理机制总结
- Java中定时任务的实现:Timer与ScheduledExecutorService的不同
- POJ 3687 拓扑排序
- 1. Two Sum
- nginx https 跳转方法
- mysql基本操作
- [IO]——编码和解码
- 线程池中CompletionService的应用
- 字符串转成整数大数乘法
- 说说JSON和JSONP,也许你会豁然开朗
- 关于string函数族实现的准备
- 计算几何----判断点是否在一个矩形内