leetcode 第一题 Two Sum


title: Leet Code TwoSum
date: 2017-07-08 23:18:54
tags:
- LeetCode
- 算法
categories: 算法


题目:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

第一反应可以把nums循环两次,用n^2的时间复杂度

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
       int n = numbers.size();
        vector<int> ans;
        for (int i = 0; i < n-1; i++) {
            for (int j = i + 1; j < n; j++) {
                if (numbers[i] + numbers[j] == target) {
                    ans.push_back(i);
                    ans.push_back(j);
                    return ans;
                }
            }
        }
        return ans;
    }
};

后来想到可以把每个数字放到Map里,总的时间复杂度可以到n。

class Solution{
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        map<int, int> mymap;
        int n = numbers.size();
        vector<int> ans;
        for(int i=0;i<n;i++){
            int t = target - numbers[i];
            if(mymap.count(t) > 0){
                ans.push_back(mymap[t]);
                ans.push_back(i);
                return ans;
            }else{
                mymap[numbers[i]] = i;
            }
        }
        return ans;
    }
};

上面程序的运行时间是9ms,打败了54.67% 。

后来看了前排6ms的代码,发现只是把map换成了unorder_map,因为map是红黑树实现的,会根据键的大小排序,查找的时间复杂度是n,而unorder_map没有排序,是hash实现的,查找的时间复杂度是常数级,因此会更快。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、题目说明 Given an array of integers, return indices of the ...
    Diffey阅读 5,104评论 4 3
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • 题目 题目的意思是在一个整形数组中查找连个数字,使其和等于给定的目标。并返回给出这两个数出现的位置。 分析 初读题...
    baixiaoshuai阅读 515评论 0 0
  • HTML笔记--表单标签 标签(空格分隔): HTML 表单标签(****最重要的一个标签*****) 可以用来实...
    醒着的码者阅读 200评论 0 0
  • 春 苹果树上浅绿色, 人们盼望它结果。 夏 苹果树上绿油油, 人们在树下乘凉。 秋 苹果树上红彤彤, 人们采下苹果...
    EEEEElectric阅读 2,121评论 1 1