zoukankan      html  css  js  c++  java
  • LeetCode 1. Two Sum

    题目:

    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换成了unordered_map,因为map是红黑树实现的,会根据键的大小排序,查找的时间复杂度是n,而unorder_map没有排序,是hash实现的,查找的时间复杂度是常数级,因此会更快。

    转载请保留原文链接及作者
    本文标题:
    文章作者: LepeCoder
    发布时间:
    原始链接:
  • 相关阅读:
    课后作业-阅读任务-阅读笔记-4
    团队编程项目作业5-小组评分
    课后作业-阅读任务-阅读提问-3
    20171110-构建之法:现代软件工程-阅读笔记
    团队-中国象棋-开发文档
    结对-贪吃蛇-结对项目总结
    20171129-构建之法:现代软件工程-阅读笔记
    课后作业-阅读任务-阅读提问-4
    软件工程课程总结
    团队-石头剪刀布-项目总结
  • 原文地址:https://www.cnblogs.com/lepeCoder/p/7230550.html
Copyright © 2011-2022 走看看