CodeWars一些积累No.1 超市排队的实现

超市排队问题(多窗口服务时间)

要求

There is a queue for the self-checkout tills at the supermarket. Your task is write a function to calculate the total time required for all the customers to check out!

input

  • customers: an array of positive integers representing the queue. Each integer represents a customer, and its value is the amount of time they require to check out.
  • n: a positive integer, the number of checkout tills.

output

The function should return an integer, the total time required.

样例

queueTime(std::vector<int>{5,3,4}, 1)
// should return 12
// because when n=1, the total time is just the sum of the times

queueTime(std::vector<int>{10,2,3,3}, 2)
// should return 10
// because here n=2 and the 2nd, 3rd, and 4th people in the 
// queue finish before the 1st person has finished.

queueTime(std::vector<int>{2,3,10}, 2)
// should return 12

我的实现方式

#include <algorithm>
#include <vector>

long queueTime(std::vector<int> customers,int n){
    std::vector<int> windows(n,0);            //用向量表示n个窗口
    int Num_Customers = customers.size();    //存储顾客的数量
    for ( int i = 0; i < Num_Customers ; i++ )
    {
        int position = min_element(windows.begin(),windows.end()) - windows.begin(); 
        //找到最小窗口的对应位置
        windows[position] += customers[i];
    }
    long MaxValue = *max_element(windows.begin(),windows.end());
    return MaxValue;

这里通过了使用vector和algorithm用来进行操作是因为可以利用min_element,和max_element函数可以实现直接找出vector中的极值元素的指针或迭代器,再利用极值元素的地址减去.begin()的地址,即可获得所需元素的下标.

另:之前在看别人的blog中看到vector下标表示只能调用不能赋值,今日亲测是可以赋值的,可能是C++后期标准允许了这一操作.

第一次写Blog,萌新勿喷.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值