【问题标题】:The best approach to get the element in Java在Java中获取元素的最佳方法
【发布时间】:2021-12-31 16:56:05
【问题描述】:

有一个电子商务网站。他们每天运行程序时,都必须返回特色产品。特色产品是当天最畅销的产品。如果有两个或多个产品被标识为特色产品,则该方法应按字母顺序对它们进行排序,然后返回最后一项。

例如

input_Products = [”redpencil”, “greenpencil”, “redpencil”, “yellowpencil”, “yellowpencil”]

对于给定的输入,输出应返回为yellowpencil

下面是我对名为getFeaturedProduct()的方法的处理方法如下

public static String getFeaturedProduct(List<String> items) {
   int length = items.size();
   Map<String, Integer> map = new HashMap<String,Integer>();

   for(int i=0; i<length; i++)
   {
       String prod = items.get(i);
       if(map.containsKey(prod))
       {
           map.put(prod, map.get(prod)+1);
       }
       else
           map.put(prod, 1);
   }

   int maxPurchasedItem = Collections.max(map.values());
   System.out.println("Max Purchased Item : " + maxPurchasedItem);

   List<String> prodNames = new ArrayList<>();
   for(Map.Entry<String, Integer> entry :map.entrySet())
   {
       if(entry.getValue() == maxPurchasedItem)
       {
           prodNames.add(entry.getKey());
       }
   }

   Collections.sort(prodNames);
   System.out.println("the featured item is : "+ prodNames.get(prodNames.size()-1));
   return prodNames.get(prodNames.size()-1);
}

您能告诉我这是最好的方法吗?这种方法的时间复杂度是多少?

【问题讨论】:

  • 您的代码可以按您的要求工作。你的问题到底是什么?
  • 你认为时间复杂度是多少?
  • @JoãoDias:我刚刚开始了解数据结构及其时间复杂度。这个问题在我的采访中被问到,当我提到这种方法时,他们问我这段代码的时间复杂度?我需要帮助了解此代码的时间复杂度或此问题的最佳解决方案。

标签: java selenium testing data-structures ui-automation


【解决方案1】:

它的时间复杂度为O(n),基本上由循环for(int i=0; i&lt;length; i++)定义。您可以在以下在线资源中阅读更多相关信息:

【讨论】:

  • 感谢您的意见。肯定会通过文件
  • 不客气。如果是,我的回答帮助您考虑支持它。谢谢! ;)
猜你喜欢
  • 1970-01-01
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
  • 2011-01-02
  • 1970-01-01
相关资源
最近更新 更多