LeetCode 01 Two Sum

题目链接
看完题目以后我只想到了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就学到了这么多。

对了,面试时我也遇到了问红黑树和平衡二叉树的区别

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值