LeetCode TwoSum题解
来源:互联网 发布:js点击滑动到相应div 编辑:程序博客网 时间:2024/06/17 00:53
题目
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].
解题思路:
利用HashMap来记录数字及对应的下标,用减法来计算判定。
代码如下:
public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(target - nums[i])) { result[1] = i ; result[0] = map.get(target - nums[i]); return result; } map.put(nums[i], i ); } return result;}
阅读全文
0 0
- LeetCode题解—TwoSum
- LeetCode TwoSum题解
- LeetCode题解——1TwoSum
- [leetcode]-twoSum
- [leetcode]twoSum
- LeetCode-TwoSum
- 【Leetcode】TwoSum
- LeetCode - TwoSum
- leetcode :twoSum
- leetcode TwoSum
- leetcode twosum
- leetcode--twoSum
- LeetCode twoSum
- LeetCode-TwoSum
- leetcode--twoSum
- leetcode TwoSum
- TwoSum leetcode
- leetcode:twosum
- IntentService详解
- 卸载 Cloudera Manager 5.1.x.和 相关软件【官网翻译:高可用】
- java学习笔记(常量 二进制 其他进制 负数进制 变量 自动类型提升 强制类型转换 )
- CCNA第一天
- 单例设计模式及反射机制破坏
- LeetCode TwoSum题解
- 多线程,成员函数内创建线程,线程函数调用类内的其他成员函数
- if-else双选择结构
- jersey+maven构建restful服务
- 一个注解引发的血案
- 百度统计不显示,什么原因?
- 浅析java中的集合类(容器)
- bootstrap-3-基本标签使用类
- Maven笔记8-Maven中使用Nexus创建私服