[LeetCode] 1. Two Sum

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里找到两个数的和为target(这两个数唯一),返回index

很快地写出一个\(O(n^2)\)的版本,可以稍微优化下,用二分查下有没有target-nums.at(i)再for循环去找index
(二分查找由于要先排序,所以无法返回index,只能判断有没有)

    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        for (int i = 0; i < nums.size(); i++)
        {
            int rest = target - nums.at(i);

            for (int j = 0; j < nums.size() && j != i; j++)
            {
                if (nums.at(j) == rest)
                {
                    result.push_back(i);
                    result.push_back(j);
                    break;
                }
            }
        }

        return result;

这种版本显然不能令人满意,使用map写出一个更快的版本

vector [2, 7, 11, 15]
map { {2, 0}, {7, 1}, {11, 2}, {15, 3} }

map的key存vector的value, map的value存vector的index
这样可以快速查到target - nums.at(i)是否存在以及index

题目里说明了这两个数唯一,所以当遇到 [3, 2, 3]这种有重复元素的vector时,target只能为6,for循环到第二个3时,程序就返回了,没有把第二个3的index存到map中去,所以用map也不会出现问题

vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        map<int, int> num_map;

        for (int i = 0; i < nums.size(); i++)
        {
            int rest = target - nums.at(i);
            if (num_map.find(rest) != num_map.end()) //map中存在该元素
            {
                result.push_back(i);
                result.push_back(num_map[rest]);
            }
            else
            {
                num_map[nums.at(i)] = i;
            }
        }

        return result;
    }

LeetCode上其他人的做法也是用的map,就不介绍了

posted @ 2018-07-25 14:02  arcsinW  阅读(143)  评论(0编辑  收藏  举报