1. Two Sum
来源:互联网 发布:淘宝联盟推广位是什么 编辑:程序博客网 时间:2024/06/06 01:21
示例
题目描述:
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, and you may not use the same element twice.
Example :
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
题目翻译
给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。
您可以假设每个输入都只有一个解决方案,而您可能不会使用相同的元素两次。
示例:
给定nums = [2,7,11,15],target = 9,因为nums [ 0 ] + nums [ 1 ] = 2 + 7 = 9,返回[ 0,1 ]。
解题方案
标签: Hash Table、Array
思路:
方法一:最简单的思路是遍历数组,看数组中剩下的数里是否存在nums[j]=target-nums[i];
方法二:将数组中的数插入HashMap中,再遍历数组,看(target-nums[i])是否在HashMap中。其时间复杂度和空间复杂度都是O(n),因为Hash Table的查找时间复杂度是O(1)。
代码:
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement) && map.get(complement) != i) { return new int[] { i, map.get(complement) }; } } throw new IllegalArgumentException("No two sum solution");}
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution");}
阅读全文
0 0
- 1. Two Sum && 167. Two Sum II
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1. Two Sum
- 1. Two Sum Ruby
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1.Two Sum
- java接口和继承
- webstorm破解
- SpringMVC从Controller跳转到另一个Controller
- 安装交叉编译工具链
- 二叉树的递归非递归遍历
- 1. Two Sum
- AngularJS入门笔记
- 如何给电脑EXE软件自定义快捷键启动?
- Maven私服搭建
- 查找--红黑树的定义
- JavaWeb项目中集成Swagger API文档
- [51nod-1119]机器人走方格V1 题解
- Jenkins安装与配置
- Druid连接池