1.两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
解答:
package com.luKun.one_100;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName Solution1
* @Description TODO
* @Author LuKun
* @Date 2022/7/3 19:14
* @Version 1.0
*/
public class Solution1 {
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[i]+nums[j]==target){
int[] results={i,j};
return results;
}
}
}
return null;
}
public int[] twoSum_Top1(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
return new int[]{map.get(target-nums[i]),i};
}
map.put(nums[i],i);
}
throw new IllegalArgumentException("No two sum solution");
}
public int[] twoSum_Top0(int[] nums, int target) {
int[] result = new int[2];
int left = 0;
int right = nums.length - 1;
Map<Integer, Integer> map = new HashMap<Integer, Integer>(nums.length);
while (left <= right) {
int leftNum = nums[left];
int rightNum = nums[right];
if (map.containsKey(leftNum)) {
int leftIndex = map.get(leftNum);
result[0] = leftIndex > left ? left : leftIndex;
result[1] = leftIndex > left ? leftIndex : left;
break;
} else {
map.put(target - leftNum, left);
}
if (map.containsKey(rightNum)) {
int rightIndex = map.get(rightNum);
result[0] = rightIndex > right ? right : rightIndex;
result[1] = rightIndex > right ? rightIndex : right;
break;
} else {
map.put(target - rightNum, right);
}
left++;
right--;
}
return result;
}
}
1、towsum是最差的一种算法,两层for循环时间复杂度直接拉满,空间复杂度也是比较高
2、towsum_Top1:我感觉是比较好的解法,时间复杂度比较低,空间复杂度也是比较低的只有一层for循环
3、towsum_Top0:这个算法的时间复杂度是我已认知的最低,但是空间复杂度要比2要高,代码执行效率是2的一倍。
总结:2、3的算法思想看实际需求来确定,如果需要空间换时间就选3