查找两数之和
来源:互联网 发布:linux初级运维招聘 编辑:程序博客网 时间:2024/05/17 04:25
题目原文:
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].
题目很简单,大意就是给你一个数组和一个目标值,要你找出数组中的两个数使得他们的和是目标值,这两个数以后定存在且不相同。
一般我们的思路就是O(n^2)的复杂度,两层循环嵌套来两两求和。但是看到推荐答案里面有一个O(n)复杂度的解法,很受启发,思路巧妙,值得贴出来:
public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < numbers.length; i++) { if (map.containsKey(target - numbers[i])) {//这里是重点,和map中存储的每个key比照,相当于一层循环 result[1] = i + 1; result[0] = map.get(target - numbers[i]); return result; } map.put(numbers[i], i + 1); } return result;}
当然,如果算上map的查找的时间耗费,复杂度肯定不止O(n)。
阅读全文
0 0
- 查找两数之和
- 查找两数之和等于给定值
- Lintcode 两数之和
- 两数之和
- 题目:两数之和
- LintCode 两数之和
- 两数之和
- 两数之和
- 两数之和
- 两数之和
- 两数之和
- 两数之和
- 两数之和I
- 两数之和II
- 两数之和III
- 两数之和 (一)
- 两数之和
- 两数之和
- 关于类成员函数中访问同类对象的私有成员
- 概念篇-SOA,ESB, JBI, SCA区别
- talkingdata
- jetty跑websocket的坑
- 为什么声明NSString属性时,一般使用Copy?
- 查找两数之和
- LINUX创建文件和目录的默认权限
- 零碎知识点记录
- spring错误 Could not resolve Spring property placeholder
- setsockopt的作用
- javabean总结
- 论文《NEURAL MACHINE TRANSLATION BY JOINTLY LEARNING TO ALIGN AND TRANSLATE》总结
- Android之捕获TextView超链接
- linux学习笔记之网络环境查看命令及测试命令