TwoSum1
2015-11-06 21:17
387 查看
问题描述
Given an array of integers, findtwo numberssuch that they
add upto a specific
target number.The function twoSum should return
indicesof the two numbers such that they add up to the target, where
index1must be less than
index2. Please note that your returned answers (both index1 and index2) are
not zero-based.
You may assume that each input would have exactly
one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
算法描述
第一种解法
首先我们用一个List<Node>存储Node,其中Node的成员变量包括val(数组中的值)和idx(数组值对应的索引+1),然后对这个List按Node.val进行排序,排序之后,我们用两个指针索引
left和
right分别从左和右来判断它们的和是否等于target。
如果等于,直接返回相应的索引(从小到大)
如果大于,right–
如果小于,left++
其代码实现如下:
public int[] twoSum(int[] nums, int target){ if(nums == null || nums.length == 0) return null; List<Node> list = new ArrayList<>(); for(int i = 0; i < nums.length; i++){ list.add(new Node(i+1, nums[i])); } list.sort(new Comparator<Node>() { @Override public int compare(Node o1, Node o2) { return o1.val - o2.val; } }); int left = 0; int right = nums.length - 1; while(left < right){ Node node1 = list.get(left); Node node2 = list.get(right); int sum = node1.val + node2.val; if(target == sum){ return new int[]{Math.min(node1.idx, node2.idx), Math.max(node1.idx, node2.idx)}; }else if(target > sum){ left++; }else { right--; } } return null; } public class Node{ int idx; int val; public Node(int idx, int val){ this.idx = idx; this.val = val; } }
第二种解法
我们采用Hash结构来存储数组中的元素val和对应的索引号idx+1。如果target - nums[i]不在Map中,则直接把nums[i]和i+1放进Map中
如果target - nums[i]在Map中,则直接返回target - nums[i]对应的
idx和
i+1
相应的代码实现:
map = new HashMap<>(); for(int i = 0; i < nums.length; i++){ int diff = target - nums[i]; if(map.containsKey(diff)){ return new int[]{map.get(diff), i+1}; } map.put(nums[i], i+1); } return null; }" data-snippet-id="ext.8d1f812753a04115df01f1e8433b920d" data-snippet-saved="false" data-csrftoken="nURvjSzt-O07nifCL6c8YxB04mRDXqTk8bHs" data-codota-status="done">[code]public int[] twoSumByHash(int[] nums, int target){ if(nums == null) return null; Map<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++){ int diff = target - nums[i]; if(map.containsKey(diff)){ return new int[]{map.get(diff), i+1}; } map.put(nums[i], i+1); } return null; }
相关文章推荐
- PHP stripos() 函数
- 红黑树插入算法实现
- ReadWriteLock用法
- 用GDB调试程序(二)
- leetcode-First Missing Positive
- iPhone屏幕尺寸
- 图片的压缩(二次采样)
- 第十章作业
- Ubuntu切换到root权限的几种方法
- js 中文显示乱码问题
- hdu5318The Goddess Of The Moon 矩阵快速幂
- R语言中如何读取Excel
- 机器学习之python基础(三)
- 惠普测试管理工具ALM使用-发布和周期
- Remoting基本原理及其扩展机制(中)
- leetcode 301 : Remove Invalid Parentheses
- centos6 不能联网
- <仅是自己做笔记。。。系列-7>输入一颗二元查找树,将该树转换为它的镜像
- Slack 开源替代品 Rocket.Chat(聊天,文件上传等等)
- 指定字节拷贝文件