均用java代码实现
题目:
给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
简单粗暴的解法:时间复杂度O(n平方)控件复杂度O(1)
public class Solution {
public static void main(String[] args) {
int []nums = { 7, 11, 15};
int target = 9;
Solution test = new Solution();
int []num=test.twoSum1(nums, target);
for(int a:num) {
System.out.print(a+" ");
}
}
public int[] twoSum1(int[] nums, int target) {
int []twoSum = new int[2];
for(int i=0;i<nums.length;i++){
if(nums.length-1==i){
return twoSum;
}
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target) {
twoSum[0] = i;
twoSum[1] = j;
return twoSum;
}
}
}
//数组里没有找到结果,抛出参数异常
throw new IllegalArgumentException("No two sum solution");
}
}
运用Map集合的解法:除去初始化,时间复杂度为O(n),空间复杂度O(n)
package com.leetCodeTest1.top100;
import java.util.HashMap;
import java.util.Map;
public class SolutionReview1 {
public static void main(String[] args) {
int []nums = { 2,7, 11, 15};
int target = 9;
SolutionReview1 sr1 = new SolutionReview1();
int []num=sr1.twoSum2(nums, target);
for(int a:num) {
System.out.print(a+" ");
}
}
// 哈希一遍法,最优
private int[] twoSum2(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
//遍历数组
for(int i=0;i<nums.length;i++) {
int complement = target - nums[i];
//判断map里是否有complement这个key
if(map.containsKey(complement)) {
//有,获得这个数的值也就是数组的下标,并与i作为数组的元素返回
return new int [] {map.get(complement),i};
}
map.put(nums[i],i );
}
//数组里没有找到结果,抛出参数异常
throw new IllegalArgumentException("No two sum solution");
}
}
两个方法的运行效果: