Counting an Occurrence in an Array (Java)

后端 未结 12 1750
情歌与酒
情歌与酒 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条回答
  •  Happy的楠姐
    2020-12-16 05:59

    You can find the answer of your question here

    I used Arrays.sort() method in my example:

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

提交回复
热议问题