java 用Java计算数组中的不同值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32444193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:12:13  来源:igfitidea点击:

Count different values in array in Java

javaarraysfor-loop

提问by RamanSB

I'm writing a code where I have an int[a] and the method should return the number of unique values. Example: {1} = 0 different values, {3,3,3} = 0 different values, {1,2} = 2 different values, {1,2,3,4} = 4 different values etc. I am not allowed to sort the array.

我正在编写一个代码,其中我有一个 int[a] 并且该方法应该返回唯一值的数量。示例:{1} = 0 个不同的值,{3,3,3} = 0 个不同的值,{1,2} = 2 个不同的值,{1,2,3,4} = 4 个不同的值等等。我不是允许对数组进行排序

The thing is that my method doesn't work probably. There is something wrong with my for statement and I can't figure it out.

问题是我的方法可能不起作用。我的 for 语句有问题,我无法弄清楚。

public class Program
{

    public static void main(String[] args)
    {
        int[] a = {1, 2, 3, 1};

        System.out.println(differentValuesUnsorted(a));
        //run: 4 //should be 3
    }

public static int differentValuesUnsorted(int[] a)
{
    int values;      //values of different numbers

    if (a.length < 2)
    {
        return values = 0;
    }else if (a[0] == a[1])
    {
        return values = 0;
    }else
    {
        values = 2;
    } 

    int numberValue = a[0];
    for (int i = a[1]; i < a.length; i++)
    {
        if (a[i] != numberValue)
        {
             numberValue++;
             values++;
        }
    }
        return values;
    }
}

Can anybody help?

有人可以帮忙吗?

回答by RamanSB

This is actually much simpler than most people have made it out to be, this method works perfectly fine:

这实际上比大多数人想象的要简单得多,这种方法非常有效:

public static int diffValues(int[] numArray){
    int numOfDifferentVals = 0;

    ArrayList<Integer> diffNum = new ArrayList<>();

    for(int i=0; i<numArray.length; i++){
        if(!diffNum.contains(numArray[i])){
            diffNum.add(numArray[i]);
        }
    }

    if(diffNum.size()==1){
            numOfDifferentVals = 0;
    }
    else{
          numOfDifferentVals = diffNum.size();
        } 

   return numOfDifferentVals;
}


Let me walk you through it:

让我带你了解一下:

1) Provide an int array as a parameter.

1) 提供一个 int 数组作为参数。

2) Create an ArrayList which will hold integers:

2) 创建一个 ArrayList 将保存整数:

  • If that arrayList DOES NOTcontain the integer with in the array provided as a parameter, then add that element in the array parameter to the array list
  • If that arrayList DOEScontain that element from the int array parameter, then do nothing. (DO NOT ADD THAT VALUE TO THE ARRAY LIST)
  • 如果该 arrayList包含作为参数提供的数组中的整数,则将数组参数中的该元素添加到数组列表
  • 如果该 arrayList确实包含来自 int 数组参数的元素,则什么都不做。(不要将该值添加到数组列表中)

N.B: This means that the ArrayList contains all the numbers in the int[], and removes the repeated numbers.

注意:这意味着 ArrayList 包含 int[] 中的所有数字,并删除重复的数字。

3) The size of the ArrayList (which is analogous to the length property of an array) will be the number of different values in the array provided.

3) ArrayList 的大小(类似于数组的长度属性)将是提供的数组中不同值的数量。



Trial

审判

Input:

输入

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

Output: 6

输出:6

回答by Saveendra Ekanayake

First create distinct value array, It can simply create using HashSet.

首先创建不同的值数组,它可以简单地使用HashSet.

Then alreadyPresent.size()will provide number of different values. But for the case such as -{3,3,3} = 0(array contains same elements); output of alreadyPresent.size()is 1. For that use this simple filter

然后alreadyPresent.size()将提供许多不同的值。但是对于诸如 - {3,3,3} = 0(数组包含相同元素)之类的情况;输出alreadyPresent.size()为 1。为此使用这个简单的过滤器

if(alreadyPresent.size() == 1)){
    return 0;
}

Following code will give the count of different values.

以下代码将给出不同值的计数。

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

public class Demo {

  public static void main(String[] args)
  {
       int array[] = {9,9,5,2,3};
       System.out.println(differentValuesUnsorted(array));
  }

  public static int differentValuesUnsorted(int[] array)
  {

     Set<Integer> alreadyPresent = new HashSet<Integer>();

     for (int nextElem : array) {
         alreadyPresent.add(nextElem);
     }

     if(alreadyPresent.size() == 1){
         return 0;
     }

     return alreadyPresent.size();

  }
}

回答by Fernando Matsumoto

You can use a HashSet, which can only contain unique elements. The HashSetwill remove the duplicated items and you can then get the size of the set.

您可以使用 a HashSet,它只能包含唯一元素。在HashSet将删除重复的项目,然后就可以得到集合的大小。

public static int differentValuesUnsorted(int[] a) {
    Set<Integer> unique = new HashSet<Integer>();
    for (int val : a) {
        unique.add(val); // will only be added if a is not in unique
    }
    if (unique.size() < 2) { // if there are no different values
        return 0;
    }
    return unique.size();
}

回答by rghome

For small arrays, this is a fast concise method that does not require the allocation of any additional temporary objects:

对于小数组,这是一种快速简洁的方法,不需要分配任何额外的临时对象:

public static int uniqueValues(int[] ids) {
    int uniques = 0;

    top:
    for (int i = 0; i < ids.length; i++) {
        final int id = ids[i];
        for (int j = i + 1; j < ids.length; j++) {
            if (id == ids[j]) continue top;
        }
        uniques++;
    }
    return uniques;
}

回答by Nitesh Seram

Try this... its pretty simple using ArrayList. You don't even need two loop. Go on

试试这个……使用ArrayList非常简单。你甚至不需要两个循环。继续

import java.util.*;
public class distinctNumbers{

 public static void main(String []args){
    int [] numbers = {2, 7, 3, 2, 3, 7, 7};
    ArrayList<Integer> list=new ArrayList<Integer>();
    for(int i=0;i<numbers.length;i++)
    {

        if(!list.contains(numbers[i]))  //checking if the number is present in the list
        {
            list.add(numbers[i]); //if not present then add the number to the list i.e adding the distinct number
        }

    }
    System.out.println(list.size());
}
}

回答by kushan raj

Try this simple code snippet.

试试这个简单的代码片段。

public static int differentValuesUnsorted(int[] a)
{
    ArrayList<Integer> list=new ArrayList<Integer>();   //import java.util.*;
    for(int i:numbers)                                  //Iterate through all the elements
      if(!list.contains(i))                             //checking for duplicate element
        list.add(i);                                    //Add to list if unique
    return list.size();
}

回答by Jan Cizmar

What about this?

那这个呢?

private <T> int arrayDistinctCount(T[] array) {
    return Arrays.stream(array).collect(Collectors.toSet()).size();
}

回答by SkyMaster

Try this:

试试这个:

import java.util.ArrayList;
public class DifferentValues {

 public static void main(String[] args)
  {
    int[] a ={1, 2, 3, 1};
    System.out.println(differentValuesUnsorted(a));
  }

 public static int differentValuesUnsorted(int[] a)
 {
   ArrayList<Integer> ArrUnique = new ArrayList<Integer>();
   int values=0;      //values of different numbers
   for (int num : a) {
       if (!ArrUnique.contains(num)) ArrUnique.add(num);
   }
   values = ArrUnique.size();
   if (values == 1) values = 0;       
   return values;
 }
}

input:{1,1,1,1,1} - output:0
input:{1,2,3,1} - output:3

输入:{1,1,1,1,1} - 输出:0
输入:{1,2,3,1} -输出:3

回答by PKuhn

Use a set to remove duplicates

使用集合删除重复项

 public static int differentValuesUnsorted(int[] a) {
     if (a.length < 2) {
         return 0;
     }

     Set<Integer> uniques = new HashSet<>(a);
     return singleUnique.size();
 }