【发布时间】:2019-01-16 05:03:15
【问题描述】:
我目前正在使用 codewars.com 来练习我的编码技能。我完成了其中一个问题,并想检查其他人的解决方案是什么,但我发现了一个我无法理解的问题。它比我的解决方案好得多,我想更多地理解它。比如“*std”究竟做了什么。 +=i 对 min_elements 做了什么以及 min 元素发生了什么?
long queueTime(std::vector<int> customers,int n){
std::vector<long> queues(n, 0);
for (int i : customers)
*std::min_element(queues.begin(), queues.end()) += i;
return *std::max_element(queues.cbegin(), queues.cend());
}
这是我的解决方案:
#include <iostream>
#include <vector>
#include <array>
using namespace std;
long queueTime(std::vector<int> customers,int n){
int i = 0; //start of Queue
int count = 0; //keeps track of how many items has been
processed
int biggest = 0; //Last/largest ending item size, add to count at end
int list [n]; //Declared number of registers by size n
for(int k = 0;k<n;k++) //sets each existing register to have 0
items
{
list[k] = 0;
}
//Start of processing customers, ends when last customer is at register.
for (auto i = customers.begin(); i!=customers.end();)
{
//checks if there are free registers.
for(int index = 0; index<n && i!=customers.end();index++)
{
if(list[index]==0)
{
list[index] = *i;
i++;
}
}
//Subtract 1 from every register
int temp=0;
for (int k =0;k<n;k++)
{
if(list[k]!= 0)
{
temp = list[k];
temp = temp-1;
list[k] = temp;
}
}
//increase count of items processed
count++;
}
//calculates the largest number of items a customer has amungst the last few
customers.
for(int j=0;j<n;j++)
{
if(list[j]>biggest)
{
biggest = list[j];
}
}
//end first part
cout<<"\nCount: "<<count<<" Biggest: "<<biggest<<endl;
cout<<"End Function:"
<<"\n************************\n***************************
*******************\n"<<endl;
//answer if number of items processed + last biggest number of items.
return count+biggest;
}
【问题讨论】:
-
这是我的解决方案:
-
std是一个命名空间。vector<T>是该命名空间的一部分,因此是引用( std:: )。 += 只是简写。x = x + 1与x += 1相同。