leedcode做题总结,题目Two Sum2011-03-13
来源:互联网 发布:淘宝网实拍保护入口 编辑:程序博客网 时间:2024/05/21 07:44
这是leedcode里最老的一道题,知道两数的和然后从一个无序的int数组中找到这两个数。一开始用两层for暴力查找果断超时了。然后修改了一下,打算排序后用二分查找第二个加数,但是要对数组进行排序,记录下每个元素的位置,也很麻烦。于是我就想到了HashMap进行查找。
使用HashMap进行查找
Map中 KEY为数组元素值,VALUE为index,这样可以迅速查找到某一元素值是否存在,和找到对应的index。代码如下:
public static int[] twoSum2(int[] numbers, int target) { HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); int[] res={-1,-1}; int num = numbers.length; for(int i=0;i<num;i++){ mp.put(numbers[i],i); } for(int j=0;j<num;j++){ int ser = target-numbers[j]; if(mp.containsKey(ser)){ res[0]=j+1; res[1]=mp.get(ser)+1; if(res[0]==res[j]||res[0]>res[j]) continue; return res; } } return res; }
Update 2015/07/22: 这次做的是历遍keySet,但是这样不如历遍原数组方便,历遍原数组可以保证顺序,不许判断两个index大小和是否有重复
public class Solution { public int[] twoSum(int[] nums, int target) { int [] res = new int[2]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i=0; i<nums.length; i++){ if (map.containsKey(nums[i]) && nums[i]*2 == target){ res[0] = map.get(nums[i]); res[1] = i+1; return res; } map.put(nums[i], i+1); } for (int key: map.keySet()){ if (map.containsKey(target - key)){ if(map.get(key) < map.get(target - key)){ res[0] = map.get(key); res[1] = map.get(target - key); }else{ res[1] = map.get(key); res[0] = map.get(target - key); } } } return res; }}
0 0
- leedcode做题总结,题目Two Sum2011-03-13
- leedcode做题总结,题目Median of Two Sorted Arrays----- 2011/03/27
- leedcode做题总结,题目Same Tree 2012/09/03
- leedcode做题总结,题目Rotate Image 2012/03/17
- leedcode做题总结,题目Reorder List 13/11/12
- leedcode做题总结, 题目Surrounded Regions130
- leedcode做题总结, 题目Median 80
- leedcode做题总结,题目Symmetric Tree 2012/09/23
- leedcode做题总结,题目Valid Palindrome 2013/01/12
- leedcode做题总结,题目Gas Station-------- 2013/09/28
- leedcode做题总结,题目Reverse Integer----- 2011/12/25
- leedcode做题总结,题目Remove Element 2012/02/16
- leedcode做题总结, 题目Permutations I/II46/47
- leedcode做题总结, 题目Longest Palindromic Substring 5
- leedcode做题总结,题目Reverse Words in a String14/03/05
- leedcode做题总结,题目Linked List Cycle I/II 13/10/28-30
- leedcode做题总结,题目Path SumI/II-------- 2012/10/13-14
- leedcode做题总结,题目ZigZag Conversion2011-12-05(wrong answer)
- 展讯平台gpio 兼容调试方法------sc8830
- 四色原型图进行业务建模的思考
- Swift中文教程(二)基本运算符
- Ubuntu14.04 安装CodeBlocks
- Swift中文教程(三) 字符串和字符
- leedcode做题总结,题目Two Sum2011-03-13
- CM9源码下载和编译
- Swift中文教程(四) 集合类型
- TortoiseSVN无法查看日志
- datatables 自定义布局
- linux下创建用户
- hdu 2896 病毒侵袭 (ac自动机)
- Solr使用入门指南
- abs, fabs, fabsf 区别