• Two Sum


    工作一年,发现自己的基础非常薄弱,对数据结构相关的知识,不够扎实。决定刷新leetcode题目,巩固下。

    题目1:Two Sum

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target,

    where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    大意:给出一个int类型的数组nums和一个数字target, 在nums里找出两个数字,其相加之和等于给target,方法twoSum返回的是这两个数的索引,

    注意这两个索引是从小到大,而且都不是从0开始的。

    一开始马上想到了个方法,用两层for循环,时间复杂度o(n^2)

    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
         for (int i = 1; i < nums.size(); i++) {
            for (int j = i + 1; j <nums.size(); j++) {
                if (nums[i] + nums[j] == target) {
                    result.push_back(i);
                    result.push_back(j);
                    return result;
                }
            }
        }
        return result;
    }
    好不疑问,这个答案肯定是错,leetcode怎么可能这么简单。
    果然,提交的时候,系统提示 Time Limit Exceeded错误
    看来,必须得将时间复杂度降到o(n),才行。
    不过,由于思路未转变,还是停留在两个for中,怎么想都想不出来,
    后来跑到讨论组里,看下别人是怎么想,发现大多数人是用map来实现的。

    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        map<int, int> temp;
        for (int i = 0; i < nums.size(); i++) {
            int value = target - nums[i];
            if (temp.count(value)) {
                int index1 = min(temp[target - nums[i]], i);
                int index2 = max(temp[target - nums[i]], i);
                result.push_back(index1 + 1);
                result.push_back(index2 + 1);
                break;
            }
            temp[nums[i]] = i;
        }
        return result;
    }

    这次通过了。

    做完后,思路一下子开通了不少,看来刷题,对于拓展思路,还是很有帮组的。

  • 相关阅读:
    poj 2000
    poj1316
    poj1922
    poj2017
    poj1833 排列
    poj1338
    poj2136
    poj2242
    IE兼容html5标签
    绑定事件后,某些情况下需要解绑该事件
  • 原文地址:https://www.cnblogs.com/the-game-over/p/4571483.html
Copyright © 2020-2023  润新知