题目:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
翻译:
给定一个整形数组和一个整数target,返回2个元素的下标,它们满足相加的和为target。
你可以假定每个输入,都会恰好有一个满足条件的返回结果。
Java版代码1(时间复杂度O(n)):
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
Integer index=map.get(target-nums[i]);
if(index==null){
map.put(nums[i],i);
}else{
return new int[]{i,index};
}
}
return new int[]{0,0};
}
}
Java版代码2(时间复杂度O(n^2)):
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result=new int[2];
for(int i=0;i<nums.length-1;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
return new int[]{i,j};
}
}
}
return result;
}
}

本文解析了一道经典算法题“两数之和”,介绍了两种解决方案:一种使用哈希表实现的时间复杂度为O(n)的方法;另一种是双重循环遍历的方法,时间复杂度为O(n^2)。
1万+





