题目:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
代码一:暴力法(核心代码)-------依次遍历查询是否有两个数之和为target,时间复杂度O(n^2),空间复杂度O(1)如果数组较长,不适用该法。
public static int[] twoSum(int[] nums, int target) {
int i,j;
for(i=0;i<nums.length;i++) {
for(j=i+1;j<nums.length;j++) {
if(nums[i]==target-nums[j]) {
//System.out.println("请输出:"+i+"和"+j);
return new int[] {i,j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
代码二:两遍哈希表,一般通过空间换时间的方法减少时间复杂度,这里我们希望能用O(1)时间判断是否存在目标元素,所以我们用哈希表,第一次遍历所有元素,将元素及其对应序列放入哈希表,第二次,我们判断目标元素是否存在并且不等于已有元素序列,时间复杂度O(n),空间复杂度O(n)因此:
class Solution {
public static 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 other=target-nums[i];
if(map.containsKey(other)&&map.get(other)!=i){//判断哈希表是否存在other,并且该序列不是i,因为题目要求不能是其本身
return new int[]{i,map.get(other)};
}
}
throw new IllegalArgumentException("No two sum solution");
}}
代码三:一次哈希表,原理同上,只是在第一次遍历同时判断元素之前是否存在目标元素,在一次遍历时完成判断过程,时间和空间复杂度均为O(n):
class 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");
}
}