繁体   English   中英

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

[英]How to get unique items from an array?

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

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

我需要得到这个输出:

1, 2, 3, 4, 5

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

但是如何获得呢?

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

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

您可以使用Set<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

在 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);
//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++;
    }
}

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

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

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

演示

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

}

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

溪流()

清楚的()

获得独特的元素。

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

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

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

你可以这样做:

    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()]之前

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

    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(", ");
        }
    }
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;
              } 
            }
         }
      }

要找出唯一数据:

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

您可以使用

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

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

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

    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 的问题时发现了这个解决方案

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

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM