LeetCode 1

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].

Solution:

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> temp;
    for(int i = 0; i < nums.size(); i++){
        if(!temp.count(target - nums[i])){
            if(!temp.count(nums[i])){
                temp[nums[i]] = i;
            }
        }else{
            return {temp[target - nums[i]], i};
        }
    }

    return {};
}

PS.

用map的运行速度不快,应该用unordered_map。

map

map是STL的一个关联容器,它提供一对一(第一个为key,每个key只能在map中出现一次,第二个为value)的数据处理能力。map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),所以在map内部所有的数据都是有序的,且map的查询、插入、删除操作的时间复杂度都是O(logN)。在使用时,mapkey需要定义operator<

unordered_map

unordered_mapmap类似,都是存储的key-value的值,可以通过key快速索引到value。不同的是unordered_map不会根据key的大小进行排序,存储时是根据keyhash值判断元素是否相同,即unordered_map内部元素是无序的。unordered_mapkey需要定义hash_value函数并且重载operator==

unordered_map的底层是一个防冗余的哈希表(采用除留余数法)。哈希表最大的优点,就是把数据的存储和查找消耗的时间大大降低,时间复杂度为O(1);而代价仅仅是消耗比较多的内存。

猜你喜欢

转载自www.cnblogs.com/QinHaotong/p/9571266.html