我正在处理来自InterviewCake [1]的编程问题,这个问题[2]令我感到困惑。
I have an array stock_prices_yesterday where:
- The indices are the time, as a number of minutes past trade
opening time, which was 9:30am local time.
- The values are the price of Apple stock at that time, in dollars.
For example, the stock cost $500 at 10:30am,
so stock_prices_yesterday[60] = 500.
提出的强力解决方案是:
The brute force ↴ approach would be to try every pair of times
(treating the earlier time as the buy time and the later time as the
sell time) and see which one is best. There are n2 such combinations,
so this will take O(n2) time.
我无法弄清楚这个解决方案将如何成为O(n2)。
如果我有一个小清单,有股票价格,比如说[21,10,43]
,那么所有可能的组合就是:
(21, 10)
(21, 43)
(10, 43)
(10, 21)
(43, 10)
(43, 21)
这不是n ** 2种组合......我相信这很简单,但它总是让我。
答案 0 :(得分:2)
这不是n ** 2种组合
Big- O 符号是最重要的因素,组合的数量(不包括重复项)(例如(10,10))仍然与 n 成比例 2 。事实上,没有重复的组合总数是 n 2 - n 。在big- O 中,您只保留最重要的术语,因此 O ( n 2 )。
通常,这组对将通过
进行枚举for i in indexes
for j in indexes
if i != j then
process(i, j)
再次为每个索引枚举所有索引:索引数乘以索引数: O ( n 2 )。< / p>