public class OperationOne {
public static void main(String[] args){
// int[] result = towSum(new int[]{2,7,11,15},9);
// System.out.println(Arrays.toString(result));
// int[] result = towSum1(new int[]{2,7,11,15},4);
// System.out.println(Arrays.toString(result));
int[] result = towSum2(new int[]{2,7,11,15},14);
System.out.println(Arrays.toString(result));
}
/**
* 题目:
* 给定一个整数数组 nums 和一个目标值 target,
* 请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
* <p>
* 你可以假设每种输入只会对应一个答案。
* 但是,你不能重复利用这个数组中同样的元素。
* <p>
* 示例:
* <p>
* 给定 nums = [2, 7, 11, 15], target = 9 / 26 / 4
* <p>
* 2 —> [7 11 15] ? 26
* 7 -> [11 15]
*/
public static int[] towSum(int[] arr,int target){
for (int i=0;i<arr.length;i++){//循环控制比较的次数
for (int j=i+1;j<arr.length;j++){//循环控制从第二个数开始
if (arr[i]+arr[j]==target) {//用数组中的第一个数和数组中的第二个数相加 也target进行比较
return new int[]{i,j} ;
}
}
}
return new int[]{-1,-1} ;//如果没有找到两个数相加等于 target的数值就返回
}
/**
* 穷举法
* 时间复杂度 O(n^2)
*/
public static int[] towSum1(int[] arr,int target){
//创建一个hashMap集合 将集合中的元素存入集合中当做集合key 数组的索引当做集合中的value
HashMap<Integer,Integer> map = new HashMap<>();
for (int i=0;i<arr.length;i++){
map.put(arr[i],i);
}
//循环数组
for (int i=0;i<arr.length;i++){
//逆推法 用target-挨个减 数组中每一个元素 然后用减出来的结果 当做集合中的key
int newTarget = target-arr[i];
//然后通过这个key 在集合中是否存在 如果在集合中存在证明也在在数组中存在
if (map.containsKey(newTarget) && map.get(newTarget)!=i){
//因为 题目规定不能用数组中元素两次进行比较 所有newTarget所对应的value不能也数组中的索引一致
return new int[]{i,map.get(newTarget)};
}
}
return new int[]{-1,-1} ;
}
/**
* 倒推法
* 通过map的数据结构 简化查询时间
* 时间复杂度 O(n)
* 2 -> 26-2=24 ? -> map{2, 7, 11, 15}
* 7 -> 26-2=19 ? -> map{2, 7, 11, 15}
*/
public static int[] towSum2(int[] arr,int target){
HashMap<Integer,Integer> map = new HashMap<>();//创建一个map集合
//一边循环向集合中条件元素 一边判断集合中是否存在计算出来的key
for (int i=0;i<arr.length;i++){
//逆推法 用target-挨个减 数组中每一个元素 然后用减出来的结果 当做集合中的key
int newTarget = target-arr[i] ;
//然后通过这个key 在集合中是否存在 如果在集合中存在证明也在在数组中存在
if (map.containsKey(newTarget)){
return new int[]{i,map.get(newTarget)};
}
map.put(arr[i],i);//为什么向集合中添加的元素放在后面???
//因为 如果查找的是 数组中每一个元素的倍数 就会出现 使用了数组中元素2次
}
return new int[]{-1,-1} ;
}
}
* 给定一个整数数组 nums 和一个目标值 target请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
最新推荐文章于 2024-02-25 10:22:41 发布