两数之和

49 阅读1分钟

leetcode.cn/problems/tw…

题目描述

image.png

解题思路

  1. 定义一个返回结构的数组并出示化
  2. 定义一个 HashMap,key 为数组中的元素,value 为数组的 index
  3. 遍历数组
  4. 当 target - 当前元素的值在 HashMap 中,将当前元素的索引下表和 HashMap 的索引下表赋值给定义的 result 数组,直接返回 result 数组。
  5. 其值不在 HashMap 时,则将当前元素的值和索引位置保存到 HashMap 中,继续循环。

代码实现

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[]{-1,-1};
        Map<Integer, Integer> numByIndex = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int numInfo = target - nums[i];
            if (numByIndex.containsKey(numInfo)) {
                result[0] = i;
                result[1] = numByIndex.get(numInfo);
                return result;
            }
            numByIndex.put(nums[i], i);
        }
        return result;
    }
}

个人微信:QTG43432166