LeetCode 第一题: 两数之和

2021-03-24 17:56:22 +08:00
 shunfy

LeetCode 第一题: 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。

#include <map>
using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int, int> tmpMap;
        int tmpNumber;
        for(int i=0, imax = nums.size(); i<imax; ++i)
        {
            tmpNumber = nums[i];
            if(tmpMap.find(tmpNumber) != tmpMap.end())
                return { tmpMap[tmpNumber], i };
            else
                tmpMap[target - tmpNumber] = i;
        }
        return {};
    }
};

以上是 Java 代码,LeetCode 执行时间是 4ms.

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> tmpMap = new HashMap<>();
        int tmpNumber;
        for(int i=0, imax = nums.length; i<imax; i++)
        {
            tmpNumber = nums[i];
            if(tmpMap.containsKey(tmpNumber))
                return new int[]{tmpMap.get(nums[i]), i};
            tmpMap.put(target - nums[i], i); 
        }
        return null;
    }
}

以上是 Java 代码,LeetCode 执行时间是 0ms.

using System.Collections.Generic;

public class Solution
{
    public int[] TwoSum(int[] nums, int target)
    {
        Dictionary<int, int> tmpTab = new Dictionary<int, int>(1);
        int tmpNumber;
        for (int i = 0, imax = nums.Length; i < imax; ++i)
        {
            tmpNumber = nums[i];
            if (tmpTab.ContainsKey(tmpNumber))
                return new int[] { tmpTab[tmpNumber], i };
            else
                tmpTab[target - tmpNumber] = i;
        }

        return null;
    }
}

以上是 CS 代码,执行时间竟然有 300ms


为什么执行时间会相差这么大呢? 是因为 LeetCode 的执行环境问题吗? 此逻辑还有优化的空间吗?

2334 次点击
所在节点    程序员
7 条回复
lewis89
2021-03-24 18:01:13 +08:00
leetcode 代码执行时间 你就当个笑话看就是了
Jirajine
2021-03-24 18:03:38 +08:00
你要比较,也得给足够大的数据集,多次运行,取平均时间,以排除冷启动、缓存等因素造成的干扰。
shunfy
2021-03-24 18:09:59 +08:00
@lewis89 你说的可能是对的
ch2
2021-03-24 18:15:13 +08:00
刘翔和博尔特比赛跑 1 米,我哨子吹完开始计时,博尔特愣了一下,成绩慢了 300ms
shpkng
2021-03-24 22:44:31 +08:00
LeetCode 同一段代码的执行速度都能差一半的
Chenamy2017
2021-03-25 09:07:13 +08:00
多跑几次,取平均值看看
obtain
2021-03-25 12:15:13 +08:00
比较时间执行的快慢没意义的,要比较写的算法时间复杂度。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/764740

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX