LeetCode Two Sum

2018-03-27  本文已影响0人  codingcyx
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].
vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        map<int, int> hash;
        for(int i = 0; i<nums.size(); i++){
            if(hash.count(target - nums[i])){
                res.push_back(hash[target-nums[i]]);
                res.push_back(i);
                break;
            }
            hash[nums[i]] = i;
        }    
        return res;
    }

使用map可以提高查找效率,使查找在近似O(n)内完成,避免了暴力查找O(n²)的复杂度。
上面的程序是边查找边在map中加数据的,也可以全部加进去之后再查找。

上一篇下一篇

猜你喜欢

热点阅读