Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中对数组中的不同值进行计数_Java_Arrays_For Loop - Fatal编程技术网

在Java中对数组中的不同值进行计数

在Java中对数组中的不同值进行计数,java,arrays,for-loop,Java,Arrays,For Loop,我正在编写一个代码,其中有一个int[a],该方法应该返回唯一值的数目。示例:{1}=0个不同的值,{3,3,3}=0个不同的值,{1,2}=2个不同的值,{1,2,3,4}=4个不同的值等等。不允许我对数组进行排序 问题是我的方法可能行不通。我的for声明有点问题,我想不出来 public class Program { public static void main(String[] args) { int[] a = {1, 2, 3, 1};

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

问题是我的方法可能行不通。我的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;
    }
}
公共类程序
{
公共静态void main(字符串[]args)
{
int[]a={1,2,3,1};
系统输出打印LN(不同值排序(a));
//run:4//应该是3
}
公共静态int差异值排序(int[]a)
{
int value;//不同数字的值
如果(a.长度<2)
{
返回值=0;
}如果(a[0]==a[1])
{
返回值=0;
}否则
{
数值=2;
} 
int numberValue=a[0];
for(int i=a[1];i

有人能帮忙吗

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

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

if(alreadyPresent.size() == 1)){
    return 0;
}
以下代码将给出不同值的计数

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

  }
}
导入java.util.array;
导入java.util.HashSet;
导入java.util.Set;
公开课演示{
公共静态void main(字符串[]args)
{
int数组[]={9,9,5,2,3};
System.out.println(差分值排序(数组));
}
公共静态int-differentivValuesSorted(int[]数组)
{
Set-alreadyPresent=new HashSet();
for(int-nextElem:array){
alreadyPresent.add(nextElem);
}
if(alreadyPresent.size()==1){
返回0;
}
返回alreadyPresent.size();
}
}

您可以使用只能包含唯一元素的
哈希集。
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();
}
public static int differentitValuesSorted(int[]a){
Set unique=新的HashSet();
for(int val:a){
unique.add(val);//仅当a不在unique中时才会添加
}
if(unique.size()<2){//如果没有不同的值
返回0;
}
返回唯一的.size();
}

使用集合删除重复项

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

     Set<Integer> uniques = new HashSet<>(a);
     return singleUnique.size();
 }
public static int differentitValuesSorted(int[]a){
如果(a.长度<2){
返回0;
}
Set uniques=新哈希集(a);
返回singleUnique.size();
}

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

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;
}
输出:6

试试这个:

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;
 }
}
import java.util.ArrayList;
公共类差异值{
公共静态void main(字符串[]args)
{
int[]a={1,2,3,1};
系统输出打印LN(不同值排序(a));
}
公共静态int差异值排序(int[]a)
{
ArrayList ArrUnique=新的ArrayList();
int values=0;//不同数字的值
for(int num:a){
如果(!ArrUnique.contains(num))ArrUnique.add(num);
}
values=arrique.size();
如果(值=1)值=0;
返回值;
}
}
输入:{1,1,1,1,1}-输出:0

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

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

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;
}
公共静态int唯一值(int[]id){
int uniques=0;
顶部:
for(int i=0;i
试试这个。。。使用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());
}
}
import java.util.*;
公共类distinctNumbers{
公共静态void main(字符串[]args){
int[]数={2,7,3,2,3,7,7};
ArrayList=新建ArrayList();

对于(inti=0;i请尝试以下简单代码片段

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();
}
public static int differentitValuesSorted(int[]a)
{
ArrayList=newArrayList();//导入java.util.*;
for(int i:numbers)//遍历所有元素
if(!list.contains(i))//检查重复元素
list.add(i);//如果唯一,则添加到列表
返回list.size();
}
这个怎么样

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

此代码格式不好,甚至无法运行。请确保您的程序没有任何编译错误,并且在发布之前格式正确。位于
DifferentitValuesSorted
顶部的那些
if
else if
else
语句是否仅用于长度小于一个2,或者他们应该遍历存储了多个int的数组?您的for循环也很糟糕。如果
a[1]
的值大于数组的长度,会发生什么情况?发生AIOOB错误可能我误解了任务,但它说(翻译成英语):如果数组为空(长度为0),该方法应返回0,因为在空数组中有0个不同的值。我一直认为这意味着,如果数组得到一个值,例如int[]a={2},则没有不同的值。因此,对于if/else if/else语句,我一直在尝试使其成为:int[
private <T> int arrayDistinctCount(T[] array) {
    return Arrays.stream(array).collect(Collectors.toSet()).size();
}