@lc app=leetcode.cn id=1java
[1] 两数之和git
leetcode-cn.com/problems/tw…github
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。算法
你能够假设每种输入只会对应一个答案。可是,你不能重复利用这个数组中一样的元素。数组
示例:app
给定 nums = [2, 7, 11, 15], target = 9post
由于 nums[0] + nums[1] = 2 + 7 = 9 因此返回 [0, 1]ui
这道题目给了咱们一个数组,还给了咱们一个目标值 target 让咱们找到两个数组,使其和为 target,乍一看这道题可使用暴力搜索,这里使用暴力搜索必然使用双重 for 循环,那这个题目的解法的时间复杂度就是 O(n^2),为了用空间换取时间,咱们只能想一个时间复杂度是 O(n) 的算法来实现,咱们既然已经决定使用线性时间复杂度来解决问题,就只能遍历遍历一个数字,可是另一个数字该怎么办呢?spa
咱们须要将其存储起来,使用 HashMap 来创建数字和坐标之间的映射,咱们知道 HashMap 是常数级别的查找效率,这样在遍历数组的时候,用 target 减去遍历到的数字,好比 target 是 4,遍历到了一个 2,那么另一个 2 不能是以前那个 2,整个实现步骤为:先遍历一遍数组,创建 HashMap 映射,而后再遍历一遍,开始查找,找到则记录 index。代码以下:code
虽然暴力破解法不是那样的完美,可是在数据规模小的时候也算是一种能够接受的方法
java 解法一:
class Solution {
public int[] twoSum(int[] nums, int target) {
// 循环遍历数组 锁定第一个值,而后在数组中找第二个值
for(int i = 0;i < nums.length; i++ ){
for(int j = i+1; j < nums.length; j++){
// 由于目标值已知,只要将目标值减去第一个数字就能获得另一个符合的数字
if(nums[j] == target - nums[i] ){
// 返回一个新的数组
return new int[]{i, j};
}
}
}
// 找不到对应的数字 抛出异常
throw new IllegalArgumentException("No two sum solution");
}
}
复制代码
JavaScript 解法一:
/** * @param {number[]} nums * @param {number} target * @return {number[]} */
let twoSum = function(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] === target - nums[j]) {
return [i,j];
}
}
}
throw new Error('No two sum solution');
};
复制代码
java 解法二:
class Solution {
public int[] twoSum(int[] nums, int target) {
// 建立一个泛型Hashmap
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
int[] res = new int[2];
// 遍历数组,将数组中的元素作一个 变成Hashmap的映射
for (int i = 0; i < nums.length; i++) {
m.put(nums[i], i);
}
for (int i = 0; i < nums.length; ++i) {
int t = target - nums[i];
// 若是在m 中找到t 而且这个元素的索引不是本身当前的索引
if (m.containsKey(t) && m.get(t) != i) {
res[0] = i;
res[1] = m.get(t);
}
}
return res;
}
}
复制代码
JavaScript 解法二:
/** * @param {number[]} nums * @param {number} target * @return {number[]} */
var twoSum = function(nums, target) {
let map = new Map();
let res = [];
// 第一遍遍历数组作map 映射
for (let i = 0; i < nums.length; i++) {
map.set(nums[i], i);
}
// 第二遍 进行查找
for (let index = 0; index < nums.length; index++) {
let t = target - nums[index];
if (map.has(t) && map.get(t) != index) {
res.push(index);
res.push(map.get(t));
break;
}
}
return res;
};
复制代码
详情请点击:原文连接