【问题标题】:How to get unique items from an array?如何从数组中获取唯一项?
【发布时间】:2020-04-30 18:55:02
【问题描述】:

我是 Java 初学者,我发现了一些关于这个主题的主题,但没有一个对我有用。 我有一个这样的数组:

int[] numbers = {1, 1, 2, 1, 3, 4, 5};

我需要得到这个输出:

1, 2, 3, 4, 5

该数组中的每个项目只有一次。

但是如何获得呢?

【问题讨论】:

标签: java arrays


【解决方案1】:

无需自己编写算法的最简单解决方案:

Integer[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> uniqKeys = new TreeSet<Integer>();
uniqKeys.addAll(Arrays.asList(numbers));
System.out.println("uniqKeys: " + uniqKeys);

设置接口保证值的唯一性。 TreeSet 还会对这些值进行排序。

【讨论】:

  • 从技术上讲,TreeSet 为您提供了解决此特定问题所需的更多信息; HashSet 就足够了。
  • @hertzsprung 我猜LinkedHashSet 会更适合这种情况。
  • 如果我有二维数组怎么办?
  • @NoOne 使用循环遍历行。在循环内部为每一行调用 addAll。
【解决方案2】:

您可以使用Set&lt;Integer&gt; 并节省大量时间,因为它包含独特的元素。如果不允许使用 Java 集合中的任何类,请对数组进行排序并计算唯一元素。您可以手动对数组进行排序或使用Arrays#sort

我会发布Set&lt;Integer&gt; 代码:

int[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for(int x : numbers) {
    setUniqueNumbers.add(x);
}
for(Integer x : setUniqueNumbers) {
    System.out.println(x);
}

请注意,我更喜欢使用 LinkedHashSet 作为 Set 实现,因为它维护元素插入的顺序。这意味着,如果您的数组是 {2 , 1 , 2},那么输出将是 2, 1 而不是 1, 2

【讨论】:

  • 感谢您的回答路易吉。这属于基础练习,所以我认为需要使用更像初学者的东西。但是,我正在尝试实现您的示例,但收到此错误:Set cannot be resolved to a type. LinkedHashSet cannot be resolved to a type 我错过任何库或类似的东西吗?谢谢
  • @user984621 您需要从 java.util 包中导入这些类。在package your.package; 句下,添加import java.util.*;
  • 你知道为什么写集合的时候不能用代替吗?
  • @Chi-YoungJeffreyLii 在 Java 中,int 是原始类型,泛型仅支持引用类型(类和接口)。 Integer 是基本 int 类型的类包装器。
  • 我的意思是什么。对于某些计算来说,使用原始数据类型似乎更容易。
【解决方案3】:

在 Java 8 中:

    final int[] expected = { 1, 2, 3, 4, 5 };

    final int[] numbers = { 1, 1, 2, 1, 3, 4, 5 };

    final int[] distinct = Arrays.stream(numbers)
        .distinct()
        .toArray();

    Assert.assertArrayEquals(Arrays.toString(distinct), expected, distinct);

    final int[] unorderedNumbers = { 5, 1, 2, 1, 4, 3, 5 };

    final int[] distinctOrdered = Arrays.stream(unorderedNumbers)
        .sorted()
        .distinct()
        .toArray();

    Assert.assertArrayEquals(Arrays.toString(distinctOrdered), expected, distinctOrdered);

【讨论】:

  • 您知道Arrays.stream(x).distinct().sorted().toArray() 是否会比Arrays.stream(x).sorted().dictinct().toArray() 表现更好吗? IE。大概前者需要排序的条目更少?
  • 在上面的代码中使用 JMH 的价值:基准模式样本得分错误单位 distinctSorted thrpt 200 465730.014 ± 2127.406 ops/s sortedDistinct thrpt 200 467130.970 ± 6364.848 ops/s
【解决方案4】:
//Running total of distinct integers found
int distinctIntegers = 0;

for (int j = 0; j < array.length; j++)
{
    //Get the next integer to check
    int thisInt = array[j];

    //Check if we've seen it before (by checking all array indexes below j)
    boolean seenThisIntBefore = false;
    for (int i = 0; i < j; i++)
    {
        if (thisInt == array[i])
        {
            seenThisIntBefore = true;
        }
    }

    //If we have not seen the integer before, increment the running total of distinct integers
    if (!seenThisIntBefore)
    {
        distinctIntegers++;
    }
}

【讨论】:

    【解决方案5】:

    下面的代码将打印唯一的整数看看:

    printUniqueInteger(new int[]{1, 1, 2, 1, 3, 4, 5});
    
    
    static void printUniqueInteger(int array[]){
        HashMap<Integer, String> map = new HashMap();
    
        for(int i = 0; i < array.length; i++){
            map.put(array[i], "test");
        }
    
        for(Integer key : map.keySet()){
            System.out.println(key);
        }
    }
    

    【讨论】:

      【解决方案6】:

      简单的散列将比任何Java内置函数高效更快

      public class Main 
      {
          static int HASH[];
          public static void main(String[] args) 
          {
              int[] numbers = {1, 1, 2, 1, 3, 4, 5};
              HASH=new int[100000];
              for(int i=0;i<numbers.length;i++)
              {
                  if(HASH[numbers[i]]==0)
                  {
                      System.out.print(numbers[i]+",");
                      HASH[numbers[i]]=1;
                  }
              }
      
          }
      }
      

      时间复杂度:O(N),其中 N=numbers.length

      DEMO

      【讨论】:

        【解决方案7】:
        public class Practice {
            public static void main(String[] args) {
                List<Integer> list = new LinkedList<>(Arrays.asList(3,7,3,-1,2,3,7,2,15,15));
                countUnique(list);
        }
        
        public static void countUnique(List<Integer> list){
            Collections.sort(list);
            Set<Integer> uniqueNumbers = new HashSet<Integer>(list);
            System.out.println(uniqueNumbers.size());
        }
        

        }

        【讨论】:

          【解决方案8】:

          在JAVA8中,你可以简单地使用

          流()

          区别()

          获取独特的元素。

          intArray = Arrays.stream(intArray).distinct().toArray();
          

          【讨论】:

          • 如果你想对该数组进行排序,请使用 Arrays.sort(intArray);获得独特元素后!
          【解决方案9】:

          有一种更简单的方法来获得不同的列表:

          Integer[] intArray = {1,2,3,0,0,2,4,0,2,5,2};
          List<Integer> intList = Arrays.asList(intArray);          //To List
          intList = new ArrayList<>(new LinkedHashSet<>(intList));  //Distinct
          Collections.sort(intList);                                //Optional Sort
          intArray = intList.toArray(new Integer[0]);               //Back to array
          

          输出:

          1 2 3 0 0 2 4 0 2 5 2   //Array
          1 2 3 0 0 2 4 0 2 5 2   //List
          1 2 3 0 4 5             //Distinct List
          0 1 2 3 4 5             //Distinct Sorted List
          0 1 2 3 4 5             //Distinct Sorted Array
          

          jDoodle Example

          【讨论】:

            【解决方案10】:

            你可以这样做:

                int[] numbers = {1, 1, 2, 1, 3, 4, 5};
                ArrayList<Integer> store = new ArrayList<Integer>(); // so the size can vary
            
                for (int n = 0; n < numbers.length; n++){
                    if (!store.contains(numbers[n])){ // if numbers[n] is not in store, then add it
                        store.add(numbers[n]);
                    }
                }
                numbers = new int[store.size()];
                for (int n = 0; n < store.size(); n++){
                    numbers[n] = store.get(n);
                }
            

            Integer 和 int 可以(几乎)互换使用。这段代码获取您的数组“数字”并对其进行更改,以便丢失所有重复的数字。如果要排序,可以在numbers = new int[store.size()]前加Collections.sort(store);

            【讨论】:

              【解决方案11】:

              我不知道你是否已经解决了你的问题,但我的代码是:

                  int[] numbers = {1, 1, 2, 1, 3, 4, 5};
                  int x = numbers.length;
                  int[] unique = new int[x];
                  int p = 0;
                  for(int i = 0; i < x; i++)
                  {
                      int temp = numbers[i];
                      int b = 0;
                      for(int y = 0; y < x; y++)
                      {
                          if(unique[y] != temp)
                          {
                             b++;
                          }
                      }
                      if(b == x)
                      {
                          unique[p] = temp;
                          p++;
                      }
                  }
                  for(int a = 0; a < p; a++)
                  {
                      System.out.print(unique[a]);
                      if(a < p-1)
                      {
                          System.out.print(", ");
                      }
                  }
              

              【讨论】:

                【解决方案12】:
                String s1[]=  {"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee"};
                
                int c=0;
                
                for(int i=0;i<s1.length;i++)
                {
                    for(int j=i+1;j<s1.length;j++)
                    {
                    if(s1[i]==(s1[j]) )
                    {
                        c++;
                    }
                    }
                        if(c==0)
                         {
                            System.out.println(s1[i]);
                         }
                            else
                             {
                            c=0;
                              } 
                            }
                         }
                      }
                

                【讨论】:

                  【解决方案13】:

                  要找出唯一数据:

                  public class Uniquedata 
                   {
                   public static void main(String[] args) 
                    {
                  int c=0;
                  
                  String s1[]={"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee","hello","hello","hybernet"};
                  
                  for(int i=0;i<s1.length;i++)
                  {
                      for(int j=i+1;j<s1.length;j++)
                      {
                      if(s1[i]==(s1[j]) )
                      {
                          c++;
                          s1[j]="";
                      }}
                          if(c==0)
                          {
                              System.out.println(s1[i]);
                          }
                              else
                              {
                                  s1[i]="";
                              c=0;    
                              }
                          }
                      }
                  }
                  

                  【讨论】:

                    【解决方案14】:

                    你可以使用

                    Object[] array = new HashSet<>(Arrays.asList(numbers)).toArray();
                    

                    【讨论】:

                    • 对于代码,你可以用反引号把它包裹起来,所以它的格式就像代码some code
                    • '' 运算符不允许用于低于 1.7 的源代码级别,因此对于较低的 JDK 版本需要将其排版为 HashSet
                    【解决方案15】:

                    这是我使用计数排序的一段代码(部分)

                    输出是由唯一元素组成的排序数组

                        void findUniqueElementsInArray(int arr[]) {
                        int[] count = new int[256];
                        int outputArrayLength = 0;
                        for (int i = 0; i < arr.length; i++) {
                            if (count[arr[i]] < 1) {
                                count[arr[i]] = count[arr[i]] + 1;
                                outputArrayLength++;
                            }
                        }
                        for (int i = 1; i < 256; i++) {
                            count[i] = count[i] + count[i - 1];
                        }
                        int[] sortedArray = new int[outputArrayLength];
                        for (int i = 0; i < arr.length; i++) {
                            sortedArray[count[arr[i]] - 1] = arr[i];
                        }
                        for (int i = 0; i < sortedArray.length; i++) {
                            System.out.println(sortedArray[i]);
                        }
                    }
                    

                    参考 - 在发现此解决方案时 试图解决一个problem from HackerEarth

                    【讨论】:

                      【解决方案16】:

                      如果您是 Java 程序员,我建议您使用它。 它会起作用的。

                      public class DistinctElementsInArray {
                      
                      //Print all distinct elements in a given array without any duplication
                      
                          public static void printDistinct(int arr[], int n) {
                      
                              // Pick all elements one by one
                              for (int i = 0; i < n; i++) {
                      
                                  // Check if the picked element is already existed
                                  int j;
                                  for (j = 0; j < i; j++)
                                      if (arr[i] == arr[j])
                                          break;
                      
                                  // If not printed earlier, then print it
                                  if (i == j)
                                      System.out.print(arr[i] + " ");
                              }
                          }
                      
                          public static void main(String[] args) {
                              int array[] = { 4, 5, 9, 5, 4, 6, 6, 5, 4, 10, 6, 4, 5, 3, 8, 4, 8, 3 };
                              // 4 - 5 5 - 4 9 - 1 6 - 3 10 - 1 3 - 2 8 - 2
                      
                              int arrayLength = array.length;
                              printDistinct(array, arrayLength);
                      
                          }
                      }
                      

                      【讨论】:

                      • 复制自 GeeksforGeeks
                      【解决方案17】:
                      public class DistinctArray {
                      
                      
                          public static void main(String[] args) {
                           int num[]={1,2,5,4,1,2,3,5};
                           for(int i =0;i<num.length;i++)
                           {
                               boolean isDistinct=false;
                               for(int j=0;j<i;j++)
                               {
                                   if(num[j]==num[i])
                                   {
                                       isDistinct=true;
                                       break;
                                   }
                               }
                               if(!isDistinct)
                               {
                                   System.out.print(num[i]+" ");
                               }
                           }
                          }
                      
                      }
                      

                      【讨论】:

                        猜你喜欢
                        • 2011-06-30
                        • 1970-01-01
                        • 1970-01-01
                        • 2023-03-28
                        • 2018-03-16
                        • 1970-01-01
                        • 2019-10-20
                        • 2020-09-21
                        相关资源
                        最近更新 更多