题目链接
看完题目以后我只想到了O(n²)方法,然后查了一下csdn博客,吃了一斤,居然能O(n)。于是自己写了一遍:
其中find的用法还是现查的。
出现的问题是应该先查找后插入,如果先插入,那么测试样例[3,1,5]都过不了,因为插入到3以后就查到了自己,但是题目要求是下标必须是不同的两个。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int,int> hmap;
for(int i=0;i<nums.size();i++)
{
if(hmap.find(target-nums[i])!=hmap.end())
{
res.push_back(hmap[target-nums[i]]);
res.push_back(i);
return res;
}
if(hmap.find(nums[i])==hmap.end())
hmap.insert(make_pair(nums[i],i));
}
}
};
AC以后看到了官方给的solution,又吃了一斤
put是什么鬼?new hashmap<>{}是什么鬼?
Approach #1 (Brute Force) [Accepted]
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
Approach #2 (Two-pass Hash Table) [Accepted]
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
Approach #3 (One-pass Hash Table) [Accepted]
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
总结来说:
这个题目标是找到集合中和为target的两个元素
目标等价于A和target-{A}两个集合寻找相同的元素
子目标就是对于A中元素a,在target-{A}中查找a
目标为子目标时间复杂度的n倍
而子目标的最小时间复杂度是O(1)
所以最终目标复杂度是O(n)
说到底,题目的关键在于
在集合中查找元素的时间复杂度最小为O(1)
具体来说,
将元素插入无需集(哈希表)的时间是O(1);在哈希表中查找元素的时间也是O(1)
将元素插入有序集(RB-tree)的时间是O(logn);在RB-tree中查找元素的时间也是O(logn)
另外标答的写法也很洋气。
没想到第一次写leetcode就学到了这么多。
对了,面试时我也遇到了问红黑树和平衡二叉树的区别