算上里面的数组元素的出​​现? (JAVA) [英] Count occurrences of elements inside array? (Java)

查看:155
本文介绍了算上里面的数组元素的出​​现? (JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力尝试,现在要弄清楚这个算法约6小时,似乎无法拿出一个解决方案。我想算一个数组中的元素的出现,并可能在两个以上单独的阵列。一个用于唯一实例,一个用于这些实例多少次发生。我发现了一些其他的在这里想对有关数组列表和包含HashMap,但我只能使用数组。

I have been working on trying to figure out this algorithm for about 6 hours now and can't seem to come up with a solution. I am trying to count the occurrences of elements inside an array and may two more separate arrays. One for the unique instances, and one for how many times these instances occurs. I found some other thinks on here about array lists and hashMaps, but I am only able to use arrays.

例如,我有这样的阵列(已排序):

For example, I have this array (already sorted):

{cats, cats, cats, dog, dog, fish}

我试图让做出实例的数组,因此:

I am trying to get make an array for the instances, so:

{cats, dog, fish}

最后,这些情况多少次发生的:

And finally, how many times these instances occur:

{3, 2, 1}

下面是code我到目前为止有:

Here is the code i have so far:

public void findArrs( String[] words )
{
  int counter = 1;
  for(int i = 0; i < words.length - 1; i++){
  if(!(words[i].equals(words[i+1]))){
  counter++; 
  }
 }

 String[] unique = new String[counter];
 int[] times = new int[counter];

 for(int i = 0; i < words.length; i++){

   }    
}

这是所有code我我所有的尝试后都有。

This is all the code I have after all my attempts.

推荐答案

假设数组至少有一个元素:

Assuming that the words array has at least one element:

int numberOfDifferentWords = 1;
String firstWord = words[0];
for(int i = 0; i < words.length; i++) {
    if(!firstWord.equals(words[i])) {
        numberOfDifferentWords++;
    }
}

// These two arrays will contain the results. 
String[] wordResultArray = new String[numberOfDiffentWords];
int[] countResultArray = new int[numberOfDiffentWords];

// This will mark where we should put the next result
int resultArrayIndex = 0;

String currentWord = firstWord;
int currentWordCount = 0;
for(int i = 0; i < words.length; i++) {
    //if we're still on the same word, increment the current word counter
    if(currentWord.equals(words[i])) {
        currentWordCount++;
    }
    //otherwise, transition to a new word
    else {
        wordResultArray[resultArrayIndex] = currentWord;
        wordCountArray[resultArrayIndex] = currentWordCount;
        resultArrayIndex++;

        currentWord = words[i];
        currentWordCount = 1;
    }
}

至于其他的答案也提到,这个问题可以通过使用列表这样一个ArrayList存储结果简化。

As other answers have mentioned, this problem could be simplified by using a List such an ArrayList to store the results.

这篇关于算上里面的数组元素的出​​现? (JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆