zoukankan      html  css  js  c++  java
  • Leetcode 1:two sum

    题目描述:

        Give an array of integers,return indices of two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution.

        Example:

        Given nums=[2,7,11,15],target=9;

        Because nums[0]+nums[1]=2+7=9;

        return [0,1].

      即给定一个整型数组和整数target,返回两个元素的下标,使他们满足相加的和等于target。你可以假定每个输入,都会恰好有一个满足条件的返回结果。

      分析:这道题我们首先想到的是暴力求解法,复杂度为O(n2)。

          第二个方法是hash,存储每个数对应的下标,复杂度为O(n)。

          第三个方法是先排序在夹逼,但是这道题要返回的是下标,因此这个方法行不通。

        以下是实现过程:

      方法一:暴力求解法

      class solution
    {
    public:
        vector<int> TwoSum(vector<int> &num, int target)
        {
            vector<int> result;
            for (int i = 0; i < num.size() - 1; ++i)
            {
                for (int j = i + 1; j < num.size(); ++j)
                {
                    if (num[i] + num[j] == target)
                    {
                        result.push_back(i + 1);
                        result.push_back(j + 1);
                    }
                }
            }
            return result;
        }
    };

      这种方法虽然很容易想到,且代码很好写,但是缺点就是时间复杂度太高。所以我们看一下另一种用hash,时间复杂度为O(n)

      方法二:

    class solution
    {
    public:
        vector<int> TwoSum(vector<int> &num, int target)
        {
            vector<int> result;
            map<int, int> Map;
            for (int i = 0; i < num.size(); ++i)    //存储每个数对应的下标
            {
                Map[num[i]] = i;
            }
            for (int i = 0; i < num.size(); ++i)
            {
                int gap = target - num[i];
                if (Map.find(gap) != Map.end())
                {
                    result.push_back(i + 1);
                    result.push_back(Map[gap]+ 1);
                    break;
                }
            }
            return result;
        }
    };

    为了降低时间复杂度,我们应该想到将逐个比较转化为直接查找,查找target与当前元素的差。而查找最快的方法是利用一个map容器存储每个元素的索引。这样取得元素索引只要常数时间即可完成。最多只需遍历一次序列,将元素及其索引加入map中,在便利的过程中进行对应差值的寻找,如果找到了就结束遍历。这样就大大减小了时间复杂度

  • 相关阅读:
    SpringMvc最全的约束——你的感冒清个人总结
    spring配置文件比较全的约束
    android 发送邮件--实现 send email for android
    android异常 More than one file was found with OS independent path 'META-INF/XXX'
    android异常 More than one file was found with OS independent path 'META-INF/XXX'
    Error:(949) Multiple substitutions specified in non-positional format; Android格式化string.xml
    Android 设置ImageView全屏
    Android 设置ImageView全屏
    git的使用之eclipse Hbuilder
    git的使用之eclipse Hbuilder
  • 原文地址:https://www.cnblogs.com/qingjiaowoxiaoxioashou/p/6374612.html
Copyright © 2011-2022 走看看