1. Two Sum
来源:互联网 发布:linux curl命令 编辑:程序博客网 时间:2024/06/05 22:59
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.
Leetcode第一题,用hashmap 可简单解。遍历数组,查找hashmap 里有没有target - nums[i], 有则返回位置,没有则把当前nums[i] 存入hashmap。代码如下:
public class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer,Integer> ht = new HashMap<Integer,Integer>(); int[] result = new int[2]; ht.put(nums[0], 0); for (int i = 1; i < nums.length; i++) { if (ht.containsKey(target - nums[i])) { result[0] = ht.get(target - nums[i]); result[1] = i; } else { ht.put(nums[i], i); } } return result; }}
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
- EditText被软键盘遮挡,所在的ScrollView不会向下滚动怎么办
- 打开首页,是SlidingMenu,想默认直接显示左侧的菜单(listview)而不是内容页(content
- android studio 异常 项目构建后R文件未生成
- Activity之间传递参数(三)
- cling开发DLNA找不到class的问题!
- 1. Two Sum
- PullToRefreshListView刷新到底部之后,会跳到开始的item,求解决方法
- textview 如何跟新值?
- 有关广播发送接收, 临近警告的问题
- unfortunately has stop
- IIS web.config url重写伪静态规则错误
- Android4.4.2编译出错
- 136. Single Number
- 在线等......xmpp