# LeetCode 一 two Sum
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].
给你一个数组和一个目标数,寻找数组中两个数相加为目标数,返回这两个数组成的数组
一般思路为两重循环取两个数相加为target的
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]=target){
result[0]=i;
result[1]=j;
break;
}
}
}
return result;
}
可以看出该算法有两重for循环 算法复杂度为O(n^2)
有没有更简单的算法呢 ?可以看出两重for循环扫了很多重复的数据,如果能够把扫过的数据存储起来,是不是可以降低复杂度呢?
如果要存储的话,存储在哪里好呢。存储在list? 似乎并没有什么变化。map? 有啥用呢?如果一个map的key-value 相加为target 扫描后面的数组是看是否有重复是不是就好了呢?
class Solution {
public int[] twoSum(int[] nums, int target) {
//定义返回数组
int[] result = new int[2];
//定义一个map
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
//result[0]是之前存进去的key对应的value
result[0]=map.get(target-nums[i]);
//result[1]肯定是当前的i
result[1]=i;
break;
}else{
//扫过一遍之后存进去
map.put(nums[i],i);
}
}
return result;
}
}
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
for i in range(len(nums)):
if dict.get(target-nums[i],None)==None:
dict[nums[i]]=i
else :
return (dict[target - nums[i]], i )
看了一眼正确答案 还好是用java写的
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");
}
抛异常也有 而且代码也简洁