Java:检查数组的相等性(顺序无关紧要) [英] Java: Checking equality of arrays (order doesn't matter)

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

问题描述

我有两个 String 数组,比方说:

I have two String arrays, let's say:

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

//这些数组应该相等

我想以最干净"的方式检查它们的相等性.

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() 使用优化的快速排序,平均为 nlog(n),但在最坏情况下为 O(n2).来自 java 文档.所以最坏的情况是 O(n2) 但实际上大多数情况下它会是 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.

    排序算法是一种经过调整的快速排序,改编自 Jon L. Bentley 和 M. Douglas McIlroy 的设计排序功能",软件实践和经验,卷.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天全站免登陆