计算数组中的出现次数

问题描述 投票:0回答:18

我知道我需要检查数组中的当前元素,看看它是否出现在数组的其他位置。这个想法是输出以下内容:

要求用户输入 10 个整数,并将这些整数分配给一个数组(因此“数字”作为该方法的参数)。假设我输入“1, 1, 2, 3, 3, 4, 5, 6, 7, 8”。打印结果应为“1 出现 2 次。2 出现 1 次。3 出现 2 次。4 出现 1 次。5 出现 1 次。6 出现 1 次。7 出现 1 次。8 出现 1 次。”此打印将通过单独的方法完成。

我的代码中的所有内容都有效,除了我创建的用于计算出现次数的方法。

public static int getOccurrences(int[] numbers)
{
    int count = 0;

    for (int i = 0; i < numbers.length; i++)
    {
        int currentInt = numbers[i];;

        if (currentInt == numbers[i])
        {
            count++;
        }
    }

    return count;
}

我知道问题出在哪里。我将数组中的当前整数元素设置为变量 currentInt。 if 语句对数组中的每个整数元素进行计数,因此输出为“[I@2503dbd3 出现 10 次。”

如何跟踪数组中每个元素的出现次数?

java arrays
18个回答
7
投票
package countoccurenceofnumbers;

import java.util.Scanner;
public class CountOccurenceOfNumbers {


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int [] num = new int[100]; 
        int [] count = new int[100];
        //Declare counter variable i
        //and temp variable that will
        //temporarily hold the value
        //at a certain index of num[] array
        int i,temp = 0;
        System.out.println("Enter the integers between 1 and 100: ");

        //Initialize num[] array with user input
        for(i=0; i < num.length; i++){
            num[i] = input.nextInt();
            //expected input will end when user enters zero
            if(num[i] == 0){
                break;
            }
        }//end of for loop

        //value at a given index of num array 
        //will be stored in temp variable
        //temp variable will act as an index value
        //for count array and keep track of number
        //of occurences of each number
        for(i = 0; i < num.length; i++){
                temp = num[i];
                count[temp]++;
            }//end of for looop

        for(i=1; i < count.length; i++){

            if(count[i] > 0 && count[i] == 1){
             System.out.printf("%d occurs %d time\n",i, count[i]);
             }
            else if(count[i] >=2){
                System.out.printf("%d occurs %d times\n",i, count[i]);
            }


         }//end of for loop

    }//end of main
    }//end of CountOccurrenceOfNumbers

///////////输出///////////////////////

输入 1 到 100 之间的整数:
2 5 6 5 4 3 23 43 2 0
2 出现 2 次
3 出现 1 次
4 出现 1 次
5 出现 2 次
6 出现 1 次
23 出现 1 次
43 出现 1 次
构建成功(总时间:3 分 23 秒)


6
投票

我们可以使用java 8 Stream API来创建频率图

Stream.of("apple", "orange", "banana", "apple")          .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.forEach(System.out::println);

下游操作本身就是一个收集器(Collectors.counting()),它对 String 类型的元素进行操作 并产生 Long 类型的结果。调用collect方法的结果是一个Map。

这将产生以下输出:

香蕉=1

橙色=1

苹果=2


3
投票

@NYB 你几乎是对的,但你必须输出计数值,并在每个元素检查时从零开始。

    int count=0,currentInt=0;
    for (int i = 0; i < numbers.length; i++)
    {
    currentInt = numbers[i];
    count=0;

       for (int j = 0; j < numbers.length; j++)
           {
             if (currentInt == numbers[j])
                {
                  count++;
                 }
            }
            System.out.println(count);
      }

@loikkk 我稍微调整了你的代码,以便打印出每个元素的出现情况。

int[] a = { 1, 9, 8, 8, 7, 6, 5, 4, 3, 3, 2, 1 };

    Arrays.sort(a);

    int nbOccurences = 1;

    for (int i = 0, length = a.length; i < length; i++) {
        if (i < length - 1) {
            if (a[i] == a[i + 1]) {
                nbOccurences++;
            }
        } else {
            System.out.println(a[i] + " occurs " + nbOccurences
                    + " time(s)"); //end of array
        }

        if (i < length - 1 && a[i] != a[i + 1]) {
            System.out.println(a[i] + " occurs " + nbOccurences
                    + " time(s)"); //moving to new element in array
            nbOccurences = 1;
        }

    }

2
投票

你需要两个循环:

  1. 从你开始的地方

  2. 一个嵌套循环,作为当前所在位置前面的一个索引,除非你位于最后。

是否有一个数字是您不希望出现在您的数组中的?如果是这样,请使用该值(例如 -1)作为哨兵值来覆盖计数的出现次数。然后,当您再次遍历数组以查找下一个数字以检查是否出现时,如果它具有您的哨兵值,则可以跳过它。


2
投票

您可以在这里找到问题的答案

我在示例中使用了

Arrays.sort()
方法:

public class MyTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

        int[] a = {1, 9, 8, 8, 7, 6, 5, 4, 3, 3, 2, 1};

        Arrays.sort(a);
        int nbOccurences = 0;

        for (int i = 0, length = a.length - 1; i < length; i++) {
            if (a[i] == a[i + 1]) {
                nbOccurences++;
            }
        }

        System.out.println("Number same occurences : " + nbOccurences);
    }
}

1
投票

最有效的方法是在迭代数组时创建hashmap来保存元素的出现次数。它将以 2n 时间复杂度完成,这对于这个问题来说是最好的 -

HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>();
int count;    
for(int i=0;i<arr.length;i++){
       if(hmap.get(arr[i])==null){
         hmap.put(arr[i],1);
       }else{
         count=hmap.get(arr[i]);
         count++;
         hmap.put(arr[i],count);
       }
     }

1
投票

这里是使用 Java 8

Stream
生成频率图的完整解决方案。注释来解释每个步骤。

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

class Scratch {
    public static void main(String[] args) {
        int[] numbers = new int[]{1, 1, 2, 3, 3, 4, 5, 6, 7, 8};

        // Count up the occurrences of each number
        final Map<Integer, Long> numberToOccurrences = getFrequencyMap(numbers);

        // Print out the results
        for (Map.Entry<Integer, Long> entry : numberToOccurrences.entrySet()) {
            System.out.println(String.format("%d occurs %d times", entry.getKey(), entry.getValue()));
        }
    }

    public static Map<Integer, Long> getFrequencyMap(int[] numbers) {
        return Arrays.stream(numbers) // Use Java 8 stream
                .boxed() // convert IntStream to Stream<Integer>
                .collect(Collectors.groupingBy(
                        Function.identity(), // Key - the number
                        Collectors.counting() // Value - occurrences of the number
                ));
    }
}

运行它打印输出

1 occurs 2 times
2 occurs 1 times
3 occurs 2 times
4 occurs 1 times
5 occurs 1 times
6 occurs 1 times
7 occurs 1 times
8 occurs 1 times

0
投票

您需要对数组中的数字进行排序。您可以使用

'sort()'
方法,它将按从小到大的顺序组织您的数字。

您还需要两个循环,一个用于与另一个进行比较。或者在我的解决方案中,我使用了“while 语句”,然后使用了“for 循环”。

我不知道我解决您问题的方法是否是您正在寻找的。也许有一个更短和/或更好的方法来解决这个问题。这就是我的想法。祝你好运!

public static int getOccurrences(int[] numbers){

    Array.sort (numbers); //sorts your array in order (i,e; 2, 9, 4, 8... becomes, 2, 4, 8, 9)

    int count = 0;
    int start = 0; 
    int move = 0;

        while(start < numbers.length){
            for (int j = 0; j < numbers.length; j++){
                int currentInt = numbers[start];;
                if (currentInt == numbers[j])
                {
                    count++;
                    move++;
                }
            }
                if(count == 1){
                    return ("Number : " + numbers[start] + " occurs " + count + " time ");
            }   else {
                    return ("Number : " + numbers[start] + " occurs " + count + " times ");
            }
                count = 0;
                start = start + move;
                move = 0;
        }
}

0
投票

只需复制并执行它,它就会给出数组中整数出现的次数。

public class noOfOccurence{  

public static void main(String[] args){

    int a[] = {1,9,4,5,6,7,5,6,7,3,2,5,7,9,0,4,3,5,1,4,6,0,2,3,1,4,3,8};

    HashSet<Integer> al = new HashSet<Integer>();

   //Store the array in set as set will store unique elemnets
    for(int i=0;i<a.length;i++){
        //int count =0; 
        al.add(a[i]);
    }
    //printing the set
    System.out.println("al "+al);


    for(int set : al){
        int count = 0;
        for(int j=0;j<a.length;j++){

            if(set==a[j]){
                count++;
            }
        }
        System.out.println(set+" occurs "+count+" times");
    }
  }
}

0
投票
import java.util.Scanner;

public class array2 {
    public static void main (String[]args) {
        Scanner input = new Scanner (System.in);
        int [] number = new int [101];
        int c;

        do {

            System.out.println("Enter the integers from 1-100");
            c = input.nextInt();
            number[c]++;

        }while (c != 0);
        for(int i = 0; i < number.length ; i++) {
            if (number[i] !=0) {
                if (number[i] == 1)
                    System.out.println(i + " occurs " + number[i] + " time");
                else
                    System.out.println(i + " occurs " + number[i] + " times "); 

            }
        }
    }
}

0
投票
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 // This program counts the number of occurrences of error message. It read the data from Excel sheet for the same.
public class fileopen {
    public static void main(String[] args) {

        String csvFile = "C:\\Users\\2263\\Documents\\My1.csv";
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ",";
        List<String> list = new ArrayList<String>();

        String[] country = null;
        Map<String, Integer> hm = new HashMap<String, Integer>();
        try {

            br = new BufferedReader(new FileReader(csvFile));
            while ((line = br.readLine()) != null) {

                // use comma as separator
                country = line.split(cvsSplitBy);

                list.add(country[2]);

                System.out.println(country[1]);
            }
            for (String i : list) {
                Integer j = hm.get(i);
                hm.put(i, (j == null) ? 1 : j + 1);
            }
            // displaying the occurrence of elements in the arraylist
            for (Map.Entry<String, Integer> val : hm.entrySet()) {
                if(val.getKey().equals("Error Message")){
                    System.out.println(val.getKey());
                    continue;
                }
                System.out.println(val.getKey() + " " + val.getValue());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

0
投票
// i use List<Integer> to solve the problem. it's not a concise way

public static List<List<Integer>> occurence(int[] cards) {

  // first, we create a ArrayList to store the distinct number and its corresponding count value
  //it takes time
  List<List<Integer>> element = new ArrayList<>();

  int tmp=cards[0],  count=0;
  int total = cards.length;

  for(int i=0; i < total; i++) {

    if(i == total -1) {
      if( cards[i] == tmp) {

          List<Integer> l = new ArrayList<>();
          l.add(tmp);
          l.add(count+1);
          element.add(l);
          break;
      }else {
        List<Integer> l = new ArrayList<>();
        l.add(tmp);
        l.add(count);
        element.add(l);

        l = new ArrayList<>();
        l.add(cards[i]);
        l.add(1);
        element.add(l);
        break;
      }

    }

    if(cards[i] == tmp) {
      count++;        
    }else { 
      List<Integer> l = new ArrayList<>();
      l.add(tmp);
      l.add(count);
      element.add(l);

      tmp = cards[i];
      count = 1;  //we already have 1 occurence of cards[i]. i.e. tmp       
    }
  }

  return element;
}

0
投票

请尝试这3种方法可能对你有帮助

方式1:有2个循环

public class Main {
    public static void main(String args[]) {
        int arr[] = {1,2,2,3,4,1,1,5,5,1};
        // Arrays.sort(arr);
        int count = 0;       
        for(int i=0;i<arr.length;i++){
            for(int j=0;j<arr.length;j++){
                if(arr[i] == arr[j]){  
                    if(j<i){
                        break;
                    }                   
                    count++;
                }               
            } 
            if(count > 0){  
                System.out.println("occurence of "+arr[i]+"  "+(count));                 
                count = 0;
            }
         }         
    }
}

方式2:有1个循环

public class Main {
    public static void main(String args[]) {
        int arr[] = {1,2,2,3,4,1,1,5,5,1};
        // Arrays.sort(arr);
        int count = 0;  
        int temp = 0;
        for(int i=0;i<arr.length;i++){              
            if(arr[count] == arr[i]){  
                 if(i<count){
                    if(count<arr.length-1)
                       count++;
                     i=0;
                        //  break;
                  }else{
                    temp++;  
                  }
            } 
                               
           if(i == arr.length-1 && temp > 0){
                System.out.println("occurence of "+arr[count]+"  "+(temp)+". "+i);                 
                temp = 0;   
            }
                  
           if(i == arr.length-1 && count<i){
               if(count<arr.length-1)
                  count++;
               i=0;                 
            }        
          }   
    }
}

方式3:使用switch语句

public class Main {
    public static void main(String args[]) {
        int arr[] = {1,2,2,3,4,1,1,5,5,1};
        // Arrays.sort(arr);
        int count = 0; 
        int temp = 0;
        for(int i=0;i<arr.length;i++){ 
              switch(0){
                  case -1:
                  default:
                    if(arr[count] == arr[i]){  
                      if(i<count){
                        if(count<arr.length-1)
                          count++;
                         i=0;
                         break;
                    }else{
                        temp++;  
                    }
                  } 
              }                  
           
            if(i == arr.length-1 && temp > 0){
                System.out.println("occurence of "+arr[count]+"  "+(temp)+". "+i);                 
                temp = 0;   
            }
                  
            if(i == arr.length-1 && count<i){
                if(count<arr.length-1)
                  count++;
                i=0;                 
            }        
         }   
    }
}

0
投票
import java.util.*;

public class noOfOccurence{  

public static void main(String[] args){
    
    int[] arr  = new int[200];
    Scanner sc = new Scanner(System.in);
    
    int n = sc.nextInt();
    Set<Integer> s = new HashSet<Integer>();
    
    for(int i = 0; i < n ; i++)
    {
        arr[i] = sc.nextInt();
        
        s.add(arr[i]);
        
    }
    
    for(int result : s)
    {
        int count = 0;
        for(int j=0; j<n; j++)
        {
            if(result == arr[j])
            {
                count++;
            }
        }
        
        if(count == 1)
        {
            System.out.println(result + " Present in " + count + " time");
        }
        else
        {
       System.out.println(result + " Present in " + count + " times");
        }
    }
    
    
    
    
}
}

0
投票

使用嵌套循环的解决方案,上面代码的结果将是一个以元素为键、出现次数为值的映射,有一个数组存储该索引是否被访问或避免在下一次迭代中被访问。

static Map<Integer, Integer> getDuplicatedCount(int[] data) {

    Map<Integer, Integer> result = new HashMap<>();
    int[] visited = new int[data.length];
    for (int i = 0; i < data.length; i++) {
        for (int j = i + 1; j < data.length; j++) {
            if (data[i] == data[j]) {
                visited[j] =-1;
                if (visited[i] !=-1) {
                    if (result.get(data[i]) == null) {
                        result.put(data[i], 2);
                    } else {
                        result.put(data[i], result.get(data[i]) + 1);
                    }
                }

            }
        }
    }
    return result;
}

0
投票

我认为这是一个您可以使用的简单代码块,您将弄清楚如何使用 util.scanner 扫描您的输入。 但目前这只是输出输入到数组中的数字及其旁边的数量。

import java.util.Arrays;

epublic class Main {
public static void main(String[] args) {


    int[] numbers = {0, 5, 3, 9, 0, 9, 0, 3};
    int[] count = new int[10];


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

        count[numbers[i]]++;
    }
    for (int j = 0; j < count.length; j++) {

        if (count[j] > 0) {

            System.out.printf("%d: %d%n", j, count[j]);

        }
    }
  }
}

0
投票

在这段代码中,我维护一个哈希图。我将迭代数字数组并将数字作为键插入,并在第一次出现时计数为 1。但是当迭代时,如果键已经存在,我将获取它的计数并加 1。最后迭代 EntrySet 并过滤值 < 2. This for printing all no of occurence's for all values and also return the key which has only 1 occurence.

public static int printSingleOccurence(int[] numbersArray){
    int singleNumber = 0;
    Map<Integer,Integer> occurenceMap = new HashMap<>();
    for(int num: numbersArray){
        if(occurenceMap.containsKey(num)){
            occurenceMap.put(num,occurenceMap.get(num)+ 1);
        }else {
            occurenceMap.put(num,1);
        }
    }

    System.out.println(occurenceMap);

    occurenceMap.entrySet().stream()
            .forEach(occurence -> {
                String string = occurence.getKey() + " occurs " + occurence.getValue() + " times ";
                System.out.println(string);
            });


    Optional<Map.Entry<Integer, Integer>> value = occurenceMap.entrySet().stream()
                .filter(entry -> entry.getValue() < 2)
                .findFirst();
    if(value.isPresent()){
        singleNumber = value.get().getKey();
    }
    return singleNumber;
}

leetcode 花了 16 毫秒。我会寻找方法来改进它


-2
投票
int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1};  

//Array fr will store frequencies of element  
int [] fr = new int [arr.length];  
int visited = -1;  
for(int i = 0; i < arr.length; i++){  
    int count = 1;  
    for(int j = i+1; j < arr.length; j++){  
        if(arr[i] == arr[j]){  
            count++;  
            //To avoid counting same element again  
            fr[j] = visited;  
        }  
    }  
    if(fr[i] != visited)  
        fr[i] = count;  
}
© www.soinside.com 2019 - 2024. All rights reserved.