-->

Thursday, November 24, 2016

1: Two Sum

https://leetcode.com/problems/two-sum/

solution:
不用hash table的话,需要double pointers. 这样的就 O(n2) 了。
使用hash table的话, 就很直观的 O(n) 了。 然后需要注意一些细节, 比如不要重复计入了, 还有就是可以扫一遍就行了 (hash的同时就可以判断了)。

代码:
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        unordered_map<int, int> map;
        for(int i=0; i<nums.size(); ++i){
            if(map.find(target-nums[i])!=map.end()&&i>map[target-nums[i]]){
                res.push_back(map[target-nums[i]]);
                res.push_back(i);
                return res;
            }
            else map[nums[i]]=i;
        }
        return res;
    }
};

1 comment :

  1. The King Casino Company - Ventureberg
    It was 출장샵 born in 1934. The Company offers luxury hotels, https://deccasino.com/review/merit-casino/ If you don't have a ventureberg.com/ poker room in your https://octcasino.com/ house, then you'll 출장안마 find a poker room in the

    ReplyDelete