JAVA实现在一个数组中找出两个数,其和为目标值

 时间:2026-02-20 08:07:02

1、算法实现:

public class TwoSum {


   /**
    * 在指定数组中找出和为 target 的两个值
    *
    * @param nums 输入数组
    * @param target 目标和
    * @return 下标及值
    */
   public Map<Integer, Integer> twoSum(int[] nums, int target){
       Map<Integer, Integer> result = new HashMap<>(16);
       Map<Integer, Integer> temp = new HashMap<>(16);
       for(int i=0;i<nums.length;i++){
           if(temp.get(target - nums[i]) != null){
               result.put(temp.get(target - nums[i]), target - nums[i]);
               result.put(i, nums[i]);
               break;
           }else {
               temp.put(nums[i], i);
           }
       }


       return result;
   }
}

2、算法测试:

public class TestTwoSum {


   @Test
   public void twoSum(){
       int[] nums = {10,34,1,2,4,6,7};
       TwoSum twoSum = new TwoSum();
       Map<Integer, Integer> integerIntegerMap = twoSum.twoSum(nums, 13);


       integerIntegerMap.forEach((key,value) ->{
           System.out.println("key:" + key + ";" + "value:" + value);
       });
   }
}

3、测试结果:

key:5;value:6

key:6;value:7

Process finished with exit code 0

  • 如何画函数y=2x^3+3x^2+2x的图像
  • java 用for语句在控制台输出数据10-1
  • html+css3+jquery多级目录树型结构菜单
  • 如何通过应用、文件在命令提示符中打开位置
  • 三国杀张角使用技巧
  • 热门搜索
    胃药什么时候吃 发膜的作用 现在有什么好看的小说 伸缩缝的作用 淘宝放单是什么意思 亭亭玉立的意思 极限挑战什么时候播 现在开什么店最赚钱 essence是什么意思 大惊失色的意思