14

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

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

我需要得到这个输出:

1, 2, 3, 4, 5

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

但是如何获得呢?

4

17 回答 17

13

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

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 还对这些值进行排序。

于 2013-04-01T21:29:52.470 回答
8

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

我将发布Set<Integer>代码:

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

于 2013-04-01T21:27:56.717 回答
5

在 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);
于 2014-07-17T13:32:11.020 回答
3
//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++;
    }
}
于 2013-04-04T21:13:12.233 回答
2

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

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);
    }
}
于 2013-04-01T21:36:03.247 回答
2

简单散列将比任何 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

演示

于 2013-04-01T21:53:55.113 回答
2
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());
}

}

于 2016-06-09T00:58:39.840 回答
1

有一种更简单的方法可以获取不同的列表:

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 示例

于 2019-08-07T07:17:03.793 回答
1

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

溪流()

清楚的()

获得独特的元素。

intArray = Arrays.stream(intArray).distinct().toArray();
于 2019-02-06T18:49:12.940 回答
0

You could do it like this:

    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 and int can be (almost) used interchangeably. This piece of code takes your array "numbers" and changes it so that all duplicate numbers are lost. If you want to sort it, you can add Collections.sort(store); before numbers = new int[store.size()]

于 2013-04-01T22:13:54.000 回答
0

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

    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(", ");
        }
    }
于 2013-04-04T21:06:23.303 回答
0

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

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

    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]);
    }
}

参考 - 在尝试解决HackerEarth 的问题时发现了这个解决方案

于 2017-04-19T10:03:49.467 回答
0

要找出唯一数据:

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;    
            }
        }
    }
}
于 2016-06-05T17:42:24.913 回答
0

如果您是 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);

    }
}
于 2020-04-30T10:36:10.750 回答
0
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;
              } 
            }
         }
      }
于 2016-06-05T17:36:30.570 回答
0

您可以使用

Object[] array = new HashSet<>(Arrays.asList(numbers)).toArray();
于 2017-01-10T19:50:32.370 回答
-1
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]+" ");
         }
     }
    }

}
于 2018-03-23T17:45:45.930 回答