Java的:数组检查平等(顺序并不重要) [英] Java: Checking equality of arrays (order doesn't matter)

查看:115
本文介绍了Java的:数组检查平等(顺序并不重要)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字符串阵列,让我们说:

I have two String arrays, let's say:

String[] s1 = {"a","b","c"}
String[] s2 = {"c","a","b"} 

//这些阵列应该是平等的。

//these arrays should be equal

我要检查他们的平等最干净的方式。

I wanted to check their equality in the "cleanest" way.

我试着用满足Arrays.equals(S1,S2),但我得到一个错误的答案。我想,这种方法关心元素的顺序,我不希望这样的事。

I tried using Arrays.equals(s1,s2) but I'm getting a false answer. I guess that this method cares about the elements' order and I don't want that to matter.

能否请你告诉我,我该怎么做,在一个不错的方式?

Can you please tell me how can I do that in a nice way?

推荐答案


  • Arrays.sort(S1);

  • Arrays.sort(S2);

  • 满足Arrays.equals(S1,S2);

如果你不想修改原来的阵列

In case you do not want to modify the original arrays

 Arrays.equals( Arrays.sort( Arrays.copyof(s1,s1.length)),
                Arrays.sort( Arrays.copyof(s2,s2.length)) );

Arrays.sort()使用在最坏情况下的平均水平,但O(n2)的一个优化的快速排序是n日志(N)。从Java文档。因此,最坏情况下,它会为O(N 2),但实际上它会为多数的情况下,O(nlogn)。

Arrays.sort() uses an optimized quick sort which is nlog(n) for average but O(n2) in worst case. From the java docs. So the worst case it will O(n2) but practically it will be O(nlogn) for most of the cases.

该排序算法是一个调谐快速排序,改编自乔恩L.宾利和M.道格拉斯麦克罗伊的工程排序功能,软件实践与经验,卷。 23(11)P。1249年至1265年(1993年11月)。此算法提供n * log(n)性能在许多数据集,导致其他快速排序会降低二次型性能。

The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance.

这篇关于Java的:数组检查平等(顺序并不重要)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆