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: }


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





  • 相关阅读:
    mysql数据库(12)--进阶二之索引
    mysql数据库(11)--进阶一之join
    mysql数据库(10)--变量、存储过程和函数
    mysql数据库(9)--视图
    mysql数据库(10)--limit与offset的用法
    前端常用在线引用地址
    SQL中ON和WHERE的区别
    jstl和e1
    解决中文乱码问题
    JSP
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078894.html
Copyright © 2011-2022 走看看