LeetCode系列之Two sum
来源:互联网 发布:金字塔软件官网 编辑:程序博客网 时间:2024/06/03 17:21
问题描述
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.
我来翻译一下:也就是给一个数组和一个两数的和,让你从这个数组中找到两个数加起来等于这个和,给出在数组中的位置
注意下一句才是重点:假设一组输入中有且只有一组满足这个条件,并且给的数组没有重复的元素
思考:
- 当然是按个遍历一遍,也就是类似于倒三角样式的遍历,复杂度n*n
for(int i = 0;i < nums.length;i++){ for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { result[0] = i; result[1] = j; break; } } }
2.思考题目中最后一句话能发现一些玄机,只有一组满足条件,并且没有重复元素,这句话就是告诉我们只用遍历一次就能得出结论,在看了别人的优解之后还是挺佩服的
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < numbers.length; i++) { if (map.containsKey(target - numbers[i])) { result[1] = i + 1; result[0] = map.get(target - numbers[i]); return result; } map.put(numbers[i], i + 1); }
- 利用map存储key的hash特性使得找key的复杂度是常数
- 利用没有重复元素使得key值唯一
- 利用只有一组解大胆return,不继续剩下的元素
大神解法链接:leetcode:two sum,id:jiaming2
阅读全文
0 0
- LeetCode系列之Two sum
- 【leetcode系列】Two Sum
- 【LeetCode】two sum系列
- leetcode之Two Sum
- LeetCode 之 Two Sum
- LeetCode之Two Sum
- LeetCode之Two Sum
- leetcode之two Sum
- leetcode之Two Sum
- leetcode 之Two Sum
- LeetCode 之 Two Sum
- LeetCode之Two Sum
- leetcode之two sum
- Leetcode之Two Sum
- leetcode之Two Sum
- leetcode之Two Sum
- leetCode之 Two Sum
- leetcode之two sum
- 分治法:二分搜索
- A Plug for UNIX POJ
- linux udp program
- HDU
- MemberCache学习
- LeetCode系列之Two sum
- spring boot1.5.X以上版本@ConfigurationProperties取消location注解后的替代方案
- HibernateDaoSupport和HibernateTemplate
- Hard problem CodeForces
- Mysql 中有关日期的函数(sql)
- Leetcode题解
- HoughLinesP( )函数详解
- Linux常用命令
- Zookeeper原子广播Zab