import java.util.Arrays;/** * 给定一个整数数组 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] * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/two-sum */public class TwoNumSum { public static int[] solve(int[] num,int target){ int[] result = new int[2]; for(int i = 0;i<num.length;i++){ for(int j = 0 ;j<num.length;j++){ if(i!=j){ if(num[i]+num[j] == target){ result[0] = i; result[1] = j; } } } } return result; } //先排序,排序完成在数组里面查找对应的下标,使用二分查找,找到了再去检索原数组 o(nlogn)+o(nlogn)+n ->o(nlogn) public static int[] solve2(int[] num,int target){ int[] result = new int[2]; int copy[] = new int[num.length]; System.arraycopy(num,0,copy,0,num.length); Arrays.sort(copy); int x =0,y =0; boolean find =false; for(int i =0;i<copy.length-1;i++) { if(copy[i]*2 <= target) { int index = Arrays.binarySearch(copy, i+1 , copy.length, target - copy[i]); if (index > 0) { find = true; x = copy[i]; y = copy[index]; } } } if(find){ for (int i =0;i<num.length;i++) { if(num[i] == x){ result[0] = i; }else if(num[i] == y){ result[1] = i; } } } return result; } //Hash表查找 O(n),预处理将数组中的数据放到HashMap中,再去找 public static int[] solve3(int[] num,int target){ int[] result = new int[2]; Map<Integer,Integer> indexMap = new HashMap<>(); for (int i = 0; i < num.length; i++) { indexMap.put(num[i],i); } for(int i=0;i<num.length;i++){ int y = target - num[i]; if(indexMap.get(y) !=null){ result[0] = i; result[1] = indexMap.get(y); } } return result; } public static void main(String[] args) { int[] num = {2,7,11,15}; int target = 9; int[] result =TwoNumSum.solve2(num,target); for(int i =0;i< result.length;i++){ System.out.println(result[i]); } }}