开发者

Check all numbers are equal

What is the best way to check that all numbers in the array (or list) are equal?

I think the solution as a loop that seek for the first unequal element ist maybe efficient, but not so elegant or readabl开发者_运维问答e. Any solutions in one line?


Any solution to this problem must run in Ω(n) time and make Ω(n) comparisons, since if this isn't the case for some sufficiently large array you wouldn't be able to look at all the elements to check that they have the same value.

Doing a linear scan of the array looking for any values different from the first one is perhaps the absolute best way to solve this problem. It makes a total of (n - 1) comparisons, which asymptotically matches the lower bound, and is both elegant and easy to implement.


Some sort of C pseudocode

i = len(list) - 1;
while (list[i] == list[i+1] && i) i--;
return i == 0;


Not one line though in the right language, I'm sure you could get it to one.

EDIT: Since you said C#...

return list.Length > 0 && list[0] == list.Aggregate(list[0], (current, i) => current & i);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜