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].
解题思路
Two Sum是一道非常高频出现的算法面试题。题目是在数组中寻找两个和为target的数。
O(N)的做法。引入一个HashMap,key为target与数组访问过的每个元素的差值,value为数组中该元素的位置。在数组中每次走一个位置,就检查HashMap,看该位置这个数是否就是前面某个数需要找来拼成target的数。不是的话,就把这个数需要的差值和该位置索引在HashMap里面登记一下。
题目中值得注意的:
- 数组并非排序数组
参考代码
public class Solution { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; HashMap<Integer, Integer> complement = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (complement.containsKey(target - nums[i])) { result[0] = complement.get(target - nums[i]); result[1] = i; return result; } complement.put(nums[i], i); } return result; } }