LeetCode01 Two Sum
2016-05-27 12:35
274 查看
有空还是刷刷leetcode,提神醒脑。
第一题,级别Easy
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:
这个题,我用的是O(n^2)的遍历,不知道有没有快速算法。我知道如果给的是排序的数组是有的。
网上看了看,有O(N)的算法。自己对Map还不是理解恨透啊。可以这样用。
public static int[] twoSumFun2(int[] nums, int target){
Map<Integer, Integer> map = new HashMap<>();
for(int i= 0 ;i<nums.length; i++){
if(map.containsKey(target - nums[i])){
return new int[]{map.get(target-nums[i]), i};
}
map.put(nums[i], i);
}
return null;
}
第一题,级别Easy
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].
这个题,我用的是O(n^2)的遍历,不知道有没有快速算法。我知道如果给的是排序的数组是有的。
public<span style="font-family: Arial, Helvetica, sans-serif; color: rgb(51, 51, 51); line-height: 30px; widows: 1;"> class TwoSum {</span> public static int[] twoSum(int[] nums, int target) { for(int i = 0; i< nums.length; i++){ for(int j=i+1; j<nums.length; j++){ if(target == nums[i]+nums[j]){ int[] result = {i,j}; return result; } } } return null; } public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = {2, 7, 11, 15}; int target = 9; int[] result = twoSum(nums, target); System.out.println("result is "+Arrays.toString(result)); } }
网上看了看,有O(N)的算法。自己对Map还不是理解恨透啊。可以这样用。
public static int[] twoSumFun2(int[] nums, int target){
Map<Integer, Integer> map = new HashMap<>();
for(int i= 0 ;i<nums.length; i++){
if(map.containsKey(target - nums[i])){
return new int[]{map.get(target-nums[i]), i};
}
map.put(nums[i], i);
}
return null;
}
相关文章推荐
- 构件图和部署图--trufun UML2推荐
- 博客搬家
- 递归转非递归几个实例
- 一般函数指针和类的成员函数指针
- Google浏览器Chrome安装失败,错误代码0xa0430721解决办法
- Android studio常见操作
- XREF
- myeclipse,eclipse,java项目中如何隐藏文件夹,如何显示文件夹
- 用栈将递归转换成非递归
- JFinal record类型数据在前台获取
- sybase存储过程,插入百万数据
- poj之旅——2010(队列)
- json 理解,添加 删除 排序
- 16. php数据库抽象层PDO(五)
- 一个项目 接口编写需要注意的地方
- 奇偶数排序(调序)
- 133. Clone Graph【M】【73】【图的遍历】【再来一遍】【vip】
- 摘要:我们经常会用到递归函数,但是如果递归深度太大时,往往导致栈溢出。而递归深度往往不太容易把握,所以比较安全一点的做法就是:用循环代替递归。文章最后的原文里面讲了如何用10步实现这个过程,相当精彩。本文翻译了这篇文章,并加了自己的一点注释和理解。
- “两学一做”知识竞赛试题(附答案)
- 荷兰国旗问题