美文网首页
[E]Leetcode1-two sum

[E]Leetcode1-two sum

作者: glassyw | 来源:发表于2017-10-14 21:07 被阅读6次

分析:

解法一:最容易想到的暴力搜索,两个循环。
时间复杂度:O(n^2)
解法二:在解法一的基础上优化一些,比如可以用两个指针(head 、tail)从前后往中间搜索。
时间复杂度:O(nlogn)
解法三:用hashmap
时间复杂度:O(n)

C++实现解法三

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        unordered_map<int,int> mymap;
        int res;
        for(int i = 0;i < nums.size();i++)
        {
            res = target - nums[i];
            unordered_map<int,int>::iterator it = mymap.find(res);
            if(it != mymap.end())
            {
                return vector<int>({it->second,i});
            }
            mymap[nums[i]] = i;
        }
    }
};

魔法

这道题形式是a+b=target(a,b未知),在写程序的时候不要限于a+b=target这种形式,换一下式子:
b=target-a
这样在搜索的时候,思考的方式会不一样,程序就变成了,搜索某个值==target。
即:a+b=target -->b=target-a

相关文章

  • [E]Leetcode1-two sum

    分析: 解法一:最容易想到的暴力搜索,两个循环。时间复杂度:O(n^2)解法二:在解法一的基础上优化一些,比如可以...

  • leetcode1-Two Sum

    问题: 解法1: 两个循环,时间复杂度O(N^2),空间复杂度O(1); 解法2:利用hash查找的特点O(1)...

  • Leetcode1-Two Sum (Python3)

    1. Two Sum Given an array of integers, returnindicesof th...

  • E战到底特训营打卡day13

    E战到底特训营打卡day13 【学习内容】:求和函数(sum,sumif,sumifs) 13.1求和函数(sum...

  • java工程师面试内容

    数据库相关: SQL中常用的函数;count() sum() avg() max() if(e1,e2,e3) ...

  • Q404 Sum of Left Leaves

    Find the sum of all left leaves in a given binary tree. E...

  • 关于Softmax的一些想法

    考虑softmax = e^{x_k} / \sum e^{x_i}���. 如果令y=e^x的话,则是一个较为一...

  • 2019-11-15

    E战到底DAY13 求和函数(SUM)&(SUMIF) SUM函数 一.基本用法 1.连续区域求和:Alt+= ...

  • leetcode简单题1-20

    Two Sum(e-1) Given an array of integers, return indices o...

  • #1 Two Sum[E]

    Description tags: Array, Hash TableGiven an array of inte...

网友评论

      本文标题:[E]Leetcode1-two sum

      本文链接:https://www.haomeiwen.com/subject/qkmtuxtx.html