1. Two Sum [Easy]

1. Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Constraints:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

思路

用HashMap来存当前值和下标,每遍历一个值的时候,用目标值和当前值得到期望值,然后去Map里找找有没有期望值,有的话直接返回当前值下标和期望值下标,没有的话就把当前值存进Map

题解

    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> recordMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int expect = target - nums[i];
            if (recordMap.containsKey(expect))
                return new int[]{recordMap.get(expect), i};
            recordMap.put(nums[i], i);
        }
        return new int[]{-1, -1};
    }
posted @ 2023-01-09 14:10  AaronTanooo  阅读(22)  评论(0)    收藏  举报