我写了下面code进行比较,有相同的元素阵列但差异秩序。
I wrote below code to compare to arrays that have same elements but in diff order.
Integer arr1[] = {1,4,6,7,2};
Integer arr2[] = {1,2,7,4,6};
例如,以上数组相等,因为它们相同的元件1,2,4,6,7。如果你有更好的$ C $下更大的阵列,请分享。
For example, Above arrays are equal as they same elements 1,2,4,6,7. If you have better code for larger arrays, please share.
修改如果独特的元素都取自两个数组,如果他们似乎是相同的,那么也是数组应该是平等的。我怎样写的code,而无需使用任何的集合类。 例:ARR1 = {1,2,3,1,2,3} ARR2 = {3,2,1}方法应返回true(=两个数组相同)
Edit If unique elements are taken from both the arrays and if they appear to be same, then also array should be equal. How do I write the code without using any collections classes. Ex: arr1={1,2,3,1,2,3} arr2={3,2,1} Method should return true (=both arrays are same).
package com.test;
public class ArrayCompare {
public boolean compareArrays(Integer[] arr1, Integer[] arr2){
if(arr1==null || arr2==null){
return false;
}
if(arr1.length!=arr2.length){
return false;
}
Integer[] sortedArr1=sortArray(arr1);
Integer[] sortedArr2=sortArray(arr2);
for(int i=0;i<sortedArr1.length-1;i++){
if(sortedArr1[i]!=sortedArr2[i]){
return false;
}
}
return true;
}
public void swapElements(Integer[] arr,int pos){
int temp=arr[pos];
arr[pos]=arr[pos+1];
arr[pos+1]=temp;
}
public Integer[] sortArray(Integer[] arr){
for(int k=0;k<arr.length;k++){
for(int i=0;i<arr.length-1;i++){
if(arr[i]>arr[i+1]){
swapElements(arr,i);
}
}
}
return arr;
}
public static void main(String[] args) {
Integer arr1[] = {1,4,6,7,2};
Integer arr2[] = {1,2,7,4,6};
ArrayCompare arrComp=new ArrayCompare();
System.out.println(arrComp.compareArrays(arr1, arr2));
}
}
推荐答案
你关心的重复计数?例如,你需要区分 {1,1,2}
和 {1,2,2}
?如果没有,只是用的HashSet
:
Do you care about duplicate counts? For example, would you need to distinguish between { 1, 1, 2 }
and { 1, 2, 2 }
? If not, just use a HashSet
:
public static boolean compareArrays(Integer[] arr1, Integer[] arr2) {
HashSet<Integer> set1 = new HashSet<Integer>(Arrays.asList(arr1));
HashSet<Integer> set2 = new HashSet<Integer>(Arrays.asList(arr2));
return set1.equals(set2);
}
如果您的执行的关心重复,那么无论您可以使用多集
从的番石榴。
If you do care about duplicates, then either you could use a Multiset
from Guava.
如果你想坚持的排序版本,为什么不使用内置的排序算法,而不是写自己的?
If you want to stick with the sorting version, why not use the built-in sorting algorithms instead of writing your own?
编辑:你甚至都不需要创建一个副本,如果你是幸福的修改现有阵列。例如:
You don't even need to create a copy, if you're happy modifying the existing arrays. For example:
public static boolean compareArrays(Integer[] arr1, Integer[] arr2) {
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
您还可以有对于其中阵列是不一样的长度的情况下的优化:
You can also have an optimization for the case where the arrays aren't the same length:
public static boolean compareArrays(Integer[] arr1, Integer[] arr2) {
// TODO: Null validation...
if (arr1.length != arr2.length) {
return false;
}
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
相关推荐
最新文章