Counting an Occurrence in an Array (Java)

后端 未结 12 1768
情歌与酒
情歌与酒 2020-12-16 05:23

I am completely stumped. I took a break for a few hours and I can\'t seem to figure this one out. It\'s upsetting!

I know that I need to check the current element in

12条回答
  •  孤城傲影
    2020-12-16 06:08

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

提交回复
热议问题