/*题目:给定一个整数数组nums和一个目标target,请你在该数组中找出合为目标值的那两个整数,并返回他们的下标 nums[]={2,7,11,15}; target=9; */
public class two_sum { //解法1、暴力枚举 public int[] twoSum(int[] nums,int target) throws IllegalAccessException { int len=nums.length; for (int i = 0; i <len-1 ; i++) {//因为第一层循环符合条件的下标不可能是最后一个,所以len-1 for (int j = i+1; j <len ; j++) { if(nums[i]+nums[j]==target){ return new int[]{i,j}; } } } throw new IllegalAccessException("no find"); } }
//测试类
public class shixian_1 { public static void main(String[] args) throws IllegalAccessException { int[] nums={2,7,11,15}; int target=9; int[] ints= new two_sum().twoSum(nums, target); for (int i = 0; i <ints.length ; i++) { System.out.println(ints[i]); } } }
//解法2、哈希表记录 public class two_sum_2 { public int[] two(int[] nums,int target){ int len=nums.length; Map<Integer,Integer> hashMap=new HashMap<>(len-1);//设定哈希表长度 hashMap.put(nums[0],0);//第一个元素肯定不是两个目标元素的最后一个,放入哈希表 for (int i = 1; i <len ; i++) { int a=target-nums[i]; if (hashMap.containsKey(a)){ return new int[]{i,hashMap.get(a)}; } hashMap.put(nums[i],i);//将不满足条件的元素及下标放入哈希表 } throw new IllegalArgumentException("no find"); } }
public class shixian_1 {
public static void main(String[] args) throws IllegalAccessException {
int[] nums={2,7,11,15};
int target=9;
int[] ints= new two_sum().twoSum(nums, target);
for (int i = 0; i <ints.length ; i++) {
System.out.println(ints[i]);
}
}
}
public class two_sum {
//解法1、暴力枚举
public int[] twoSum(int[] nums,int target) throws IllegalAccessException {
int len=nums.length;
for (int i = 0; i <len-1 ; i++) {//因为第一层循环符合条件的下标不可能是最后一个,所以len-1
for (int j = i+1; j <len ; j++) {
if(nums[i]+nums[j]==target){
return new int[]{i,j};
}
}
}
throw new IllegalAccessException("no find");
}
}
//解法2、哈希表记录
public class two_sum_2 {
public int[] two(int[] nums,int target){
int len=nums.length;
Map<Integer,Integer> hashMap=new HashMap<>(len-1);//设定哈希表长度
hashMap.put(nums[0],0);//第一个元素肯定不是两个目标元素的最后一个,放入哈希表
for (int i = 1; i <len ; i++) {
int a=target-nums[i];
if (hashMap.containsKey(a)){
return new int[]{i,hashMap.get(a)};
}
hashMap.put(nums[i],i);//将不满足条件的元素及下标放入哈希表
}
throw new IllegalArgumentException("no find");
}
}
题目链接:力扣