gpt4 book ai didi

c++ - 为什么两个C++函数具有相同的概念,但运行时却大不相同?

转载 作者:行者123 更新时间:2023-12-01 14:52:30 25 4
gpt4 key购买 nike

leetcode的问题:https://leetcode.com/problems/remove-element/

我的答案:

算法1-使用时间:

    int removeElement(std::vector<int>& nums, int val) {
if (nums.empty()){ return 0; }
int i = 0, j = 0; // two pointers
while (j < nums.size()){
if (nums[j] == val){
j++; // skip the value to be removed
} else {
nums[i] = nums[j]; // copy the value to a previous cell
i++;
j++;
}
}
return i;
}

别人的答案。

算法2-用于:

        int removeElement(vector<int>& nums, int val) {
int l=nums.size();
int k=0;
for(int i=0;i<l;i++)
{
if(nums[i]!=val)
{
nums[k]=nums[i];
k++;
}
}
return k;
}

第一个答案 (算法1)具有 8ms运行时,第二个答案 (算法2) 4ms运行时。从我看到的实现是相同的。

为什么运行时不同?

行为不一致

另外, (算法1)的运行时不一致:第一个提交具有 8ms运行时,第二个和第三个提交具有 4ms运行时,最后一个具有 0ms运行时。这种行为与Leetcode的平台有关吗?
My screenshot of 4 submissions

最佳答案

我认为您应该重新考虑您的要求。我在您的上第一个回答上获得了 4ms 运行时:

enter image description here

关于c++ - 为什么两个C++函数具有相同的概念,但运行时却大不相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62232717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com