如何将包含重复元素的数组作为集合进行比较?

3
我有两个数组,可能会有重复的元素。我需要将它们作为集合进行比较。
例如,{1, 4, 9, 16, 9, 7, 4, 9, 11} 等同于 {11, 11, 7, 9, 16, 4, 1}。我已经尝试了很多方法,但是一直得到错误或错误的答案。以下是我现在的代码:
import java.util.Scanner;
public class sameElement{
  public static void main(String[] args){
        int[] value1 = {11, 7, 9, 16, 4, 1};
        int[] value2 = {11, 11, 7, 9, 16, 4, 1};
   sort(value1);
   sort(value2);
   System.out.println(sameSet(value1, value2));

   }
public static boolean sameSet(int[] a, int[] b){
int j = 0;
int counter2 = 0;
for(int i = 0; i < b.length; i++){
  if(a[j] == b[i]){j++;}
  else{counter2++;};}

   }
public static int[] sort (int[] a){
  for (int i = 0; i < a.length; i++) {
    for (int i2 = i + 1; i2 < a.length; i2++){
        if (a[i] > a[i2]){
          int temp = a[i2];
          a[i2] = a[i];
          a[i] = temp;}
         }
     }
return a;
 }
}

你需要检查给定数组中的重复项是否在同一位置,还是可以在任何位置? - Prathap
我原本计划对其进行排序并清除所有重复项,然后检查数组是否相同。但是我无法弄清楚。 - user1687879
1
使用两个Set<Integer>,并测试两个集合是否相等。 - JB Nizet
这是我的教科书中的一个练习问题,我只是为我的考试做准备哈哈。 - user1687879
6个回答

5

TreeSet是一个有序的集合,因此它将免费进行排序和去重。因此,您只需要将数组加载到其中,然后使用.equals()方法即可。

Integer[] value1 = { 11, 7, 9, 16, 4, 1 };
Integer[] value2 = { 11, 11, 7, 9, 16, 4, 1 };

Set<Integer> tSet1 = new TreeSet<Integer>(Arrays.asList(value1));
Set<Integer> tSet2 = new TreeSet<Integer>(Arrays.asList(value2));

System.out.println(tSet1);
System.out.println(tSet2);

System.out.println(tSet1.equals(tSet2));

输出

[1, 4, 7, 9, 11, 16]
[1, 4, 7, 9, 11, 16]
true

1
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.HashSet;
import java.util.Set;


public class Test {
    public static class SameElement {
        /**
         * Constructor.
         */
        private SameElement()
        {
            // avoid instatiation
        }

        /**
         * Check if the provided 2 arrays have the same elements ignoring order and duplicates
         * 
         * @param val1 1st array
         * @param val2 2nd array
         * @return true if so.
         */
        public static boolean sameSet(int[] val1, int[] val2)
        {
            return toSet(val1).equals(toSet(val2));
        }

        /**
         * Transform provided array of int into a {@link Set} of {@link Integer}.
         * 
         * @param vals Array of int to use
         * @return a {@link Set} of {@link Integer} (empty if vals is null)
         */
        private static Set<Integer> toSet(int[] vals)
        {
            final Set<Integer> set = new HashSet<Integer>();
            if (vals != null) {
                for (final int i : vals) {
                    set.add(i);
                }
            }
            return set;
        }
    }

    @org.junit.Test
    public void testSameSet()
    {
        int[] value1 = { 11, 7, 9, 16, 4, 1 };
        int[] value2 = { 11, 11, 7, 9, 16, 4, 1 };
        int[] value3 = { 8, 11, 11, 7, 9, 16, 4, 1 };
        assertTrue(SameElement.sameSet(value1, value2));
        assertFalse(SameElement.sameSet(value3, value1));
        assertFalse(SameElement.sameSet(value3, value2));
        assertFalse(SameElement.sameSet(null, value2));
        assertFalse(SameElement.sameSet(value1, null));
        assertTrue(SameElement.sameSet(null, null)); // check against your requirements
    }
}

1

0
        int[] value1 = {11, 7, 9, 16, 4, 1};
        int[] value2 = {11, 11, 7, 9, 16, 4, 1};
        HashSet<Integer> set = new HashSet<Integer>();
        HashSet<Integer> set2 = new HashSet<Integer>();

           for(int i=0; i<value1.length;i++) {
                  set.add(value1[i]);
           }
        for(int j=0; j<value2.length; j++) {
                 set2.add(value2[j]);
           }
          now do the sorting and compare both the sets

如果您将value2中的元素插入到一个集合中,它会删除重复项,因为集合不允许重复。 - PermGenError
set1不存在,为什么要使用LinkedHashSet - user180100
@chaitanya10 现在看起来没问题了。正如 RC 的答案中所提到的,您现在可以使用 Set 的 equals() 方法来比较值。 - jan.vdbergh
@chaitanya10 如果之后进行排序,我认为就不需要保持顺序了。 - user180100
使用LinkedHashSet 是浪费。只需使用HashSet,因为您不关心顺序并且想要唯一性。 - Dez Udezue
显示剩余2条评论

0

我修改了你的sameSet方法,它不需要对数组进行排序,并且可以处理重复项而不会将它们删除。

public static boolean sameSet(int[] a, int[] b)
{
    for (int i = 0; i < a.length; i++)
    {
        boolean match = false;
        for (int j = 0; j < b.length; j++)
        {
            if (a[i] == b[j])
            {
                match = true;
                break;
            }
        }
        if (!match)
            return false;
    }
    return true;
}

我有很多优化的空间,但目前已经达到了预期的目的。


0
以下是我编写的代码。
  1. 检查数组长度以确定最大值。
  2. 使用最大的数组作为外循环。
  3. 对于最大数组中的每个元素,迭代小数组。
  4. 检查每个元素是否未找到,如果未找到,则声明为不相等。
以下是代码。
public static void main(String[] args) {

    int[] value1 = { 11, 7, 9, 16, 4, 1 };
    int[] value2 = { 11, 11, 7, 9, 16, 4, 1 };

    int[] firstArray = null;
    int[] secondArray = null;
    //Max Length Array should be used for outer loop
    if(value2.length >value1.length)
    {
        firstArray = value2;
        secondArray = value1;
    }
    else
    {
        firstArray = value1;
        secondArray = value2;
    }
    boolean equal = true;
    for (int i = 0; i < firstArray.length; i++) {
        boolean found = false;//each iteration initialise found to false
        for (int j = 0; j < secondArray.length; j++) {
            if (firstArray[i] == secondArray[j]) {
                found = true;
                break;// as there is no point running the loop
            }

        }
        if (!found) {
            equal = false;//check after each iteration if found is false if false arrays are not equal and break
            break;
        }

    }
    System.out.println(equal);


}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接