【LeetCode】1. Two Sum 两数之和(JAVA)

题目地址: https://leetcode.com/problems/two-sum/

题目描述:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

题目大意

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

解题方法

用空间换时间,先用Map把以前的数据存下来,再寻找存不存在,不存在就存入Map,存在直接返回结果(Accepted)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            Integer temp = map.get(target - nums[i]);
            if (temp == null) {
                map.put(nums[i], i);
            } else {
                return new int[]{temp, i};
            }
        }
        return new int[]{0, 0};
    }
}
	执行用时      内存消耗
	  2 ms	     41.2 MB
发布了29 篇原创文章 · 获赞 3 · 访问量 1119

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104503970