【问题标题】:Solving: How many shops are open at a certain time?解决:某个时间有多少家商店开门?
【发布时间】:2012-11-21 11:35:55
【问题描述】:

我在一次采访中被提出了这个问题,但从未真正想出一个很好的解决方案。有人有“最佳”解决方案吗?目标是效率和能够处理大量输入。

提供的材料:

给了我一长串商店及其开/关时间(比如 1000 个)。

问题:

对于一天中的给定时间,返回有多少商店在营业

示例数据:

Sainsburys 10:00 23:00
Asda 02:00 18:00
Walmart 17:00 22:00

输入/输出示例

Input | Output
12:00 | 2
22:00 | 1 (walmart shut @ 22:00)
17:30 | 3

问题的两个部分是如何存储数据以及如何有效地得到答案,我猜你如何读取输入等并不重要。

感谢您的时间和洞察力!

【问题讨论】:

    标签: algorithm scheduling


    【解决方案1】:

    让我们试一试:

    //First, we turn the time input into an int and then compare it to the open and
    //closing time ints to determine if the shop is open. We'l use 10:00 in this example.
    //get magic time int
    int magicTimeInt = CInt("10:00".Replace(":",""));
    int openstorecount = 0;
    foreach(var shoptime in ShopTimesList)//SHopTImesList is the list of shop names and times
    {
        string[] theShop = shoptime.Split(" ");
        if( CInt(theshop[1].ToString().Replace(":", "")) < magicTimeInt 
        && 
        CInt(theshop[2].ToString().Replace(":", "")) > magicTimeInt)
        {
            openstorecount++;
        }
    }
    Console.WriteLine("10:00 | " + openstorecount.ToString());
    

    【讨论】:

      【解决方案2】:

      我会使用数据库:

      TABLE shops (
       name VARCHAR,
       open TIME,
       close TIME
      )
      
      SELECT count(*) AS number_of_shops FROM shops WHERE [input_time] BETWEEN open AND close
      

      为了防止查询计算 walmart(在您的示例中),您可以添加一秒来打开并从关闭中减去一秒(或者几分钟让任何人有机会购买东西)。

      【讨论】:

        【解决方案3】:

        我会用 Java 做:

        class Shop {
            String name;
            Time opening, closing;
        
            Shop(String name; Time opening, Time closing){
                this.name = name;
                this.opening = opening;
                this.closing = closing;
            }
        
            public boolean isOpen(Time time){
                return opening.before(time) && closing.after(time)
            }
        }
        

        添加代码以从时间值中删除日期信息,然后收集所有商店、迭代并增加每个打开的商店的计数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多