—————第二天——————你是什么意思?让我们举个例子。
给定以下整数数组(标题假定该数组中没有重复的元素):我们随机选择一个特定值,例如13,并要求查找两个数字之和等于13的所有组合。
从12开始+1 = 13,6 + 7 = 13,最终输出结果(输出为下标)如下:[1,6] [2,7]肖辉想要表达的想法是遍历整个数组直接,每次遍历一个元素时,都会将其添加到其他元素中以查看总和是否等于该特定值。
在第一轮中,添加元素5和其他元素:找不到满足要求的两个元素。
在第二轮中,元素12与其他元素相加:发现相加后的结果12和1为13,符合要求。
根据这个想法,整个数组都被遍历了。
————————————让我们详细演示:在第一轮中,访问元素5并计算13-5 = 8。
在哈希表中搜索8,发现找不到它:在第二轮中,访问元素12,并计算13-12 = 1。
在哈希表中查找1,发现元素1的下标为6,因此元素12(下标为1)和元素1(下标为6)是一对结果:第3轮,访问元素6,计算出Out 13-6 = 7。
在哈希表中查找7,发现元素7的下标为7,因此元素6(下标为2)和元素7(下标为7)是一对结果:根据此思想,整个数组具有被遍历了。
公共类FindSumNumbers {public static List> twoSum(int [nums,int target)Map map = new HashMap();放。
List(num)List = Array = List()的新值; 1(int)i],i);对于(int i = 0; i int other = target-nums [i]; Array.res(add)(map.containsKey(other)if(map.containsKey(other))(map.containsKey(other)).asList (i,map.get(other)));结果ListRemove(nums [i]); Remove(nums [i]); Remove(nums [i]); Remove(nums [i]); Remove(nums [i] ])static void main(String [] args){int [] nums = {5,12,6,3,9,2,1,7}; List> resultList = twoSum(nums,13); list:resultList: ){System.out.println(Arrays.toString(list.toArray()));}}}}}}}}}}}}}}}}}}}}}}}}}}} System.out.println(Arrays.toString(list.toArray())“);}}”公共静态列表> twoSumV2(int [] nums,“ int Map;” ultMap; List = newMap; List = newMap; Nums,int Map; new ArrayList(); for(int i = 0; i int other = tar t-nums [ i]; if(map.containsKey(other)){resultList.add(Arrays.asList(map.get(other),i))(map.get(other),i);放(map.i)(map .containsKey(other))return resultList;中秋节快到了,小慧为大家准备了一份福利,扫一扫跟随下面的官方账号,回复关键字“奶茶”,您就可以参加彩票:单击[现在],这是对小慧的最大支持!