博文中会简要介绍Leetcode P0001题目分析及解题思路。
“Two Sum”是一道很经典的题目,在Amazon的面试中出现比较多,题干直白易懂。在数组中找到两个数使其加和为target
。
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.
为了在将复杂度控制O(n),需要思考如何记忆已经查询过的数,否则就会需要重复查询。简单来讲就是cache
思维,以空间换时间。将已经查询过的数记忆在某个数据结构X
中,然后每次在数组中新查询一个数都在X
内查找是否有加和为target
的数。
由于返回的是下标,所以自然想到用键值对来存储,所以数据结构X
则是HashTable
。
以下是Java的题解代码实现。
以下是C++的题解代码实现。