LeetCode之两数之和
2018-03-31 11:10
211 查看
题目
给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。
你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 1 到 n,不是以 0 开头。
注意事项
你可以假设只有一组答案。
样例
给出 numbers = [2, 7, 11, 15], target = 9, 返回 [1, 2].
思路
思路一:暴力解法,两次for循环,遍历所有可能,这也是容易想到的方法,时间复杂度O(n^2),空间复杂度O(1);
思路二:利用哈希表,每次存储target减去当前数的差值(key),当前值的下标(value),当再碰到这个值时,即找到了符合要求的值。时间复杂度O(n),空间复杂度O(n);
代码
//思路一暴力解法
//思路二利用哈希表
转自博客:https://blog.csdn.net/C_calary/article/details/75052639
给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。
你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 1 到 n,不是以 0 开头。
注意事项
你可以假设只有一组答案。
样例
给出 numbers = [2, 7, 11, 15], target = 9, 返回 [1, 2].
思路
思路一:暴力解法,两次for循环,遍历所有可能,这也是容易想到的方法,时间复杂度O(n^2),空间复杂度O(1);
思路二:利用哈希表,每次存储target减去当前数的差值(key),当前值的下标(value),当再碰到这个值时,即找到了符合要求的值。时间复杂度O(n),空间复杂度O(n);
代码
//思路一暴力解法
public int[] twoSum(int[] numbers, int target) { // write your code here int[] a = new int[2]; for (int i = 0; i < numbers.length - 1; i++){ for (int j = i + 1; j < numbers.length; j++ ){ if (numbers[i] + numbers[j] == target){ a[0] = i + 1; a[1] = j + 1; break; } } } return a; }
//思路二利用哈希表
public int[] twoSum(int[] numbers, int target) { int[] a = new int[2]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < numbers.length; i++){ if (map.containsKey(numbers[i])){ a[0] = map.get(numbers[i]); a[1] = i + 1; return a; } //存储差值为key,下标为value(题目要求从1开始故+1) map.put(target - numbers[i], i + 1); } return a; }
转自博客:https://blog.csdn.net/C_calary/article/details/75052639
相关文章推荐
- [leetcode, python] Two Sum 两数之和等于某数
- [LeetCode] 653. Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树
- 排序相关—— 相邻两数的最大差值( Maximum Gap-LeetCode)
- leetcode 两数之和 II - 输入有序数组 python
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- [leetcode, python] Two Sum 两数之和等于某数
- 单排leetcode(python3)-两数之和
- [LeetCode] Divide Two Integers 两数相除
- Leetcode002--单链表两数相加
- LeetCode 1. Two Sum(两数之和)
- LeetCode两数之和
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- [leetcode, python] Two Sum 两数之和等于某数
- leetCode两数之和
- LeetCode 2. Add Two Numbers(两数相加)
- 链表:链表两数相加( LeetCode 2. Add Two Numbers(两数相加))
- leetcode算法题:两数相加(Java实现-效率超过100%提交者)
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- Leetcode 两数之和
- [leetcode, python] Two Sum 两数之和等于某数