The Supermarket Queue

2017-12-27  本文已影响0人  Magicach

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!

The function has two input variables:

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

EDIT:A lot of people have been confused in the comments. To try to prevent any more confusion:

Good Solution1:

import java.util.Arrays;
public class Solution {

    public static int solveSuperMarketQueue(int[] customers, int n) {
      int[] result = new int[n];
      for(int i = 0; i < customers.length; i++){
        result[0] += customers[i];
        Arrays.sort(result);
      }
      return result[n-1];
    }
    
}

Good Solution2:

import java.util.*;
public class Solution {

    public static int solveSuperMarketQueue(int[] customers, int n) {
      if (customers.length == 0)
        return 0;
      
      PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
      for (int i = 0; i < customers.length && i < n; i++)
        pq.offer(customers[i]);
      
      for (int i = n; i < customers.length; i++)
        pq.offer(pq.poll() + customers[i]);
        
      while (pq.size() != 1) 
        pq.poll();
      
      return pq.poll();
    }
    
}
上一篇下一篇

猜你喜欢

热点阅读