TwoSum问题:
①、twosum输入不存在相同数据,输出唯一
问题描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
解决方案:
1)、使用暴力解决方法,使用嵌套遍历,找到对应元素下标
2)、使用散列表,具体描述如下:
首先设置一个map容器 record,用来记录元素的值和索引,然后遍历数组:
-》每次遍历数组的时候,使用临时变量complement,保存目标值与当前值的差值
-》在此遍历中查找record,查看是否与complement一致,如果查找成功,则返回当前查找值的索引和当前遍历值i
-》如果没有找到,则在record中保存元素值和下标 i
代码如下:时间复杂度 O(n),空间复杂度 O(n)
// 按照上述流程,代码如下
public int[] twosum(int[] nums, int target){
// 用于存储数组值(key)和下标(value)
HashMap<Integer, Integer> record = new HashMap<>();
// 存储结果下标数组
int[] res = new int[2];
// 开始遍历
for (int i = 0; i <nums.length ; i++) {
// 目标与当前值差值
int complement = target - nums[i];
// 判断map中是否存在差值
if(record.containsKey(complement)){
// 保存当前下标,并退出
res[0] = i;
res[1] = record.get(complement);
break;
}
// 将当前值存入hash中
record.put(nums[i], i);
}
return res;
}
②、twosum问题:输入不存在相同数,但输出的对数不唯一
整数数组 nums 中有多对整数相加可以得到 target,根据①的实现方式,只要遍历完整个数组即可。
代码如下:时间复杂度 O(n),空间复杂度 O(n)
public ArrayList<int[]> twosum_output_contain_duplication(int[] nums, int target){
// 存储输出结果
ArrayList<int[]> arrayList = new ArrayList<>();
// 值和下标的映射
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < nums.length ; i++) {
int t = target - nums[i];
if(hashMap.containsKey(t)){
// 添加目标值
int[] res = new int[2];
res[0] = i;
res[1] = hashMap.get(t);
// 保存输出结果
arrayList.add(res);
}
hashMap.put(nums[i], i);
}
return arrayList;
}
③、输入整数存在重复的情况
整数数组 nums 中有多对整数相加可以得到 target,并且输入整数有相同整数相加可以得到target,有两种思路:
-》先对数组进行排序,然后从头往后开始找符合要求的整数,可以使用一个头指针pBegin和尾指针pEnd遍历数组
-》直接从头往后遍历,使用头指针pBegin和尾指针pEnd,遍历整个数组
第一种方法将数组打乱了,会出现结果与原数组不匹配;第二种方法就是暴力求解,两种方法的时间复杂度都是O(n^2),针对第二种方法代码如下:(假如大佬有更好的方法,希望在评论区告知,谢谢)
public ArrayList<int[]> twosum_input_contain_duplication(int[] nums, int target){
// 存储结果
ArrayList<int[]> arrayList = new ArrayList<>();
// 定义两个指针,pBegin头指针,pEnd尾指针
int pOld = 0;
int pBegin = 0;
int pEnd = nums.length - 1;
// 开始从头遍历
while(pBegin < pEnd){
// 保存当前pEnd值
pOld = pEnd;
// 先固定pBegin,从后往前查找
while(pBegin < pEnd ){
// 找到相加等于target的整数
if(nums[pBegin] + nums[pEnd] == target){
int[] res = new int[2];
res[0] = pBegin;
res[1] = pEnd;
arrayList.add(res);
}
pEnd--;
}
pEnd = pOld;
pBegin++;
}
return arrayList;
}
本文探讨TwoSum问题的不同场景及解决方案,包括输入不存在重复数据时的唯一解法,以及输入存在重复数据时的多种解法。提供了详细的算法描述与示例代码。
2001

被折叠的 条评论
为什么被折叠?



