两数之和

两数之和:给定目标值,求数组中两数之和等于目标值的元素下标。

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         HashMap<Integer, Integer> hm = new HashMap<>();
 4         for(int i = 0; i < nums.length; i ++) {
 5             int x = target - nums[i];
 6             if(hm.containsKey(x)) {
 7                 return new int[] {hm.get(x), i};
 8             }
 9             else {
10                 hm.put(nums[i], i);
11             }
12         }
13         return new int[] {-1, -1};
14     }
15 }

 

posted @ 2021-10-10 17:24  一塌糊涂的小废物  阅读(88)  评论(0)    收藏  举报