Two Sum
来源:互联网 发布:php usleep 性能 编辑:程序博客网 时间:2024/06/06 08:48
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].
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int rest = target - nums[i]; if (map.containsKey(rest)) { return new int[] {map.get(rest),i}; } map.put(nums[i], i); } throw new IllegalArgumentException("不存在"); }
可以去官网测试,或者
public static void main(String[] args) { int[] nums={2,3,4}; int target=6; TwoSum ts=new TwoSum(); System.out.println(Arrays.toString(ts.twoSum(nums, target))); System.out.println(nums); }
额外说一点:最后的输出一个输出数组,另一个则会输出哈希值
0 0
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- HDOJ 2846 Repository
- poj2084Game of Connections 卡特兰数
- LongAdder与AtomicInteger并发性能的简单比较测试
- php基础知识
- mysql sql语句调优及,索引总结
- Two Sum
- ORACLE 在线移动redo log路径、删除无效的redo log
- 理解数据结构
- leetcode 506. Relative Ranks
- 初级数据结构简总结
- JAVA求学之路第十二天(接口)
- 基础js代码
- 文章标题
- $.ajax几种数据数据类型的异步请求