数组:算法(1)—— 两数之和

 题目描述:

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

题解思路

 利用 hashmap 进行计算,map 的 key 存具体值,value 存放序号,遍历数组,如果 key 存在(目标值 - 当前值),返回 value 和当前序号,反之存入

代码

 1     public int[] twoSum(int[] nums, int target) {
 2         HashMap<Integer, Integer> map = new HashMap<>();
 3         for (int i = 0; i < nums.length; i ++) {
 4             if (map.containsKey(target - nums[i])) {
 5                 return new int[] {map.get(target - nums[i]), i};
 6             }
 7             map.put(nums[i], i);
 8         }
 9         return new int[0];
10     }

 

posted @ 2021-12-14 11:03  墨梅青莲  阅读(59)  评论(0)    收藏  举报