如何从数组中获取唯一项?

时间:2013-04-01 21:26:27

标签: java arrays

我是Java初学者,我找到了一些关于这个主题的主题,但它们都没有为我工作。 我有一个像这样的数组:

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

我需要获得此输出:

1, 2, 3, 4, 5

该阵列中的每个项目只需一次。

但是如何得到它?

17 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:7)

您可以使用Set<Integer>并节省大量时间,因为它包含唯一元素。如果不允许使用Java Collections中的任何类,请对数组进行排序并计算唯一元素。您可以手动对数组进行排序,也可以使用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

答案 2 :(得分: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);

答案 3 :(得分: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);
    }
}

答案 4 :(得分:2)

//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 :(得分: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());
}

}

答案 6 :(得分:1)

简单哈希将远远超过任何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 :(得分: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);

    }
}

答案 8 :(得分:0)

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

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

答案 9 :(得分:0)

在JAVA8中,您只需使用

  

stream()

  

distinct()

获得独特的元素。

# convert to datetime first if not done already
df['OP Date'] = pd.to_datetime(df['OP Date'])

df.sort_values('OP Date').groupby(['Name', 'ID'])['OP Date'].agg(['first', 'last'])


             first       last
Name ID                      
Jann 1  2001-01-01 2018-01-01
     2  2001-01-01 2001-01-01
Kay  1A 2002-01-01 2002-01-01

答案 10 :(得分: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]);
    }
}

参考 - 发现了这个解决方案 试图解决problem from HackerEarth

答案 11 :(得分:0)

你可以使用

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

答案 12 :(得分: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;    
            }
        }
    }
}

答案 13 :(得分: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;
              } 
            }
         }
      }

答案 14 :(得分: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(", ");
        }
    }

答案 15 :(得分:0)

你可以这样做:

    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可以(几乎)互换使用。这段代码将您的数组“数字”并更改它,以便丢失所有重复的数字。如果您想对其进行排序,可以在Collections.sort(store);

之前添加numbers = new int[store.size()]

答案 16 :(得分:-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]+" ");
         }
     }
    }

}