leetcode题解-167. Two Sum II
来源:互联网 发布:mysql防注入 编辑:程序博客网 时间:2024/04/28 16:21
题目:
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must 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 and you may not use the same element twice.Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2
其实和Two Sum一样,只不过给的数组是排好序的而已,且返回索引从1开始,所以我们提出下面三种解决方案:
- 双指针法
- map法
- binary search法
第一种方法,两个指针分别从0和length-1开始遍历,然后求和两个数,如果等于target就返回,如果大于则right–,否则left++。代码如下所示:
public int[] twoSum(int[] numbers, int target) { int [] res = new int [2]; int left = 0, right = numbers.length-1; while(left < right){ int tmp = numbers[left] + numbers[right]; if(tmp == target){ res[0] = left + 1; res[1] = right + 1; break; }else if(tmp < target) left ++; else right --; } return res; }
另外一种方法就是使用map来保存遍历过的数组信息,与Two Sum原理相同。代码入下:
public int[] twoSum1(int[] numbers, int target) { Map<Integer, Integer> map = new HashMap<>(); int [] res = new int[2]; for(int i=0; i<numbers.length; i++){ if(map.containsKey(numbers[i])){ res[0] = map.get(numbers[i]); res[1] = i+1; break; }else map.put(target-numbers[i], i+1); } return res; }
方法三是使用binary search,其实跟方法一思路很相近,这里就不再进行赘述。
0 0
- leetcode题解-167. Two Sum II
- LeetCode-167. Two Sum II
- leetcode 167. Two Sum II
- [leetcode]167. Two Sum II
- leetcode 167. Two Sum II
- leetcode 167. Two Sum II
- LeetCode | 167. Two Sum II
- LeetCode:167. Two Sum II
- [LeetCode]167. Two Sum II
- [LeetCode]167. Two Sum II
- LeetCode 167. Two Sum II
- LeetCode 167. Two Sum II
- [leetcode]: 167. Two Sum II
- LeetCode 167. Two Sum II
- 【Leetcode】167. Two Sum II
- [leetcode]167. Two Sum II
- LeetCode 167. Two Sum II
- LeetCode 167. Two Sum II
- C程序设计大赛B题
- java File类
- scala相关通则
- 160. Intersection of Two Linked Lists
- 在这个领域苹果谷歌都已落后 亚马逊才是真正的王者
- leetcode题解-167. Two Sum II
- Linux学习41_每天一个linux命令(33):df 命令
- HDU2546 饭卡
- 缓存各种问题汇总:缓存雪崩和缓存穿透等问题
- Ubuntu14.04.05+win10双系统安装以及遇到的问题和解决办法
- Unity 5 中的全局光照技术
- ADB操作
- 微软CEO:人工智能应该帮助而非取代劳动者
- 关于很多新人询问ClassNotFoundException和MethodNotFoundException如何解决