假设我有以下数组:
views = [
{ :user_id => 1, :viewed_at => '2012-06-29 17:03:28 -0400' },
{ :user_id => 1, :viewed_at => '2012-06-29 17:04:28 -0400' },
{ :user_id => 2, :viewed_at => '2012-06-29 17:05:28 -0400' },
{ :user_id => 3, :viewed_at => '2012-06-29 17:06:28 -0400' },
{ :user_id => 1, :viewed_at => '2012-06-29 17:07:28 -0400' },
{ :user_id => 1, :viewed_at => '2012-06-29 17:08:28 -0400' },
{ :user_id => 3, :viewed_at => '2012-06-29 17:09:28 -0400' },
{ :user_id => 3, :viewed_at => '2012-06-29 17:16:28 -0400' },
{ :user_id => 3, :viewed_at => '2012-06-29 17:26:28 -0400' },
{ :user_id => 3, :viewed_at => '2012-06-29 17:36:28 -0400' },
{ :user_id => 1, :viewed_at => '2012-06-29 17:47:28 -0400' },
{ :user_id => 2, :viewed_at => '2012-06-29 17:57:28 -0400' },
{ :user_id => 3, :viewed_at => '2012-06-29 17:67:28 -0400' },
{ :user_id => 1, :viewed_at => '2012-06-29 17:77:28 -0400' }
]
假设数组按viewed_at排序
如果我想检索特定user_id的views数组中的最后一个视图哈希,我可以执行以下操作:
views.reverse.detect { |view| view[:user_id] == 1 }
其中检测将返回块评估为真的可枚举中的第一项。
我的问题是:我假设反向O(n)
方法是有成本的,那么我怎样才能反向检测而不必反转阵列?还是相反的方法不是?O(n)