zoukankan      html  css  js  c++  java
  • [LeetCode] Two Sum, Solution


    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
    » Solve this problem

    [Thoughts]
    两种解法。
    解法一, hash
    从左往右扫描一遍,然后将数及坐标,存到map中。然后再扫描一遍即可。时间复杂度O(n)

    解法二,双指针扫描
    将数组排序,然后双指针从前后往中间扫描。时间复杂度O(n*lgn)。因为是要求返回原数组的下标,所以在排序的时候还得有额外的数组来存储下标信息, 也挺麻烦。

    解法三,暴力搜索
    这个倒是最省事的。时间复杂度O(n*n)

    解法一实现如下:
    1:    vector<int> twoSum(vector<int> &numbers, int target) {  
    2: map<int, int> mapping;
    3: vector<int> result;
    4: for(int i =0; i< numbers.size(); i++)
    5: {
    6: mapping[numbers[i]]=i;
    7: }
    8: for(int i =0; i< numbers.size(); i++)
    9: {
    10: int searched = target - numbers[i];
    11: if(mapping.find(searched) != mapping.end())
    12: {
    13: result.push_back(i+1);
    14: result.push_back(mapping[searched]+1);
    15: break;
    16: }
    17: }
    18: return result;
    19: }

    解法二
    1:       struct Node  
    2: {
    3: int val;
    4: int index;
    5: Node(int pVal, int pIndex):val(pVal), index(pIndex){}
    6: };
    7: static bool compare(const Node &left, const Node &right)
    8: {
    9: return left.val < right.val;
    10: }
    11: vector<int> twoSum(vector<int> &numbers, int target) {
    12: vector<Node> elements;
    13: for(int i =0; i< numbers.size(); i++)
    14: {
    15: elements.push_back(Node(numbers[i], i));
    16: }
    17: std::sort(elements.begin(), elements.end(), compare);
    18: int start = 0, end = numbers.size()-1;
    19: vector<int> result;
    20: while(start < end)
    21: {
    22: int sum = elements[start].val + elements[end].val;
    23: if(sum == target)
    24: {
    25: result.push_back(elements[start].index+1);
    26: if(elements[start].index < elements[end].index)
    27: result.push_back(elements[end].index+1);
    28: else
    29: result.insert(result.begin(),elements[end].index+1);
    30: break;
    31: }
    32: else if(sum > target)
    33: end--;
    34: else
    35: start++;
    36: }
    37: return result;
    38: }


    解法三,两个循环嵌套搜索,不写了。





  • 相关阅读:
    [PY3]——heap模块 和 堆排序
    [PY3]——求TopN/BtmN 和 排序问题的解决
    [转载+补充][PY3]——环境配置(2)——windows下安装pycharm并连接Linux的python环境
    [转载+补充]windows下SVN客户端的安装
    [Visual studio code 常见问题解决] ——中文乱码、
    Smrty模版总结(转)
    cms内容模型标签
    phpcms图文总结(转)
    phpcms总结(转)
    PHP总结
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078894.html
Copyright © 2011-2022 走看看