Counting repeated elements in an integer array

前端 未结 13 1316
挽巷
挽巷 2020-11-27 08:02

I have an integer array crr_array and I want to count elements, which occur repeatedly. First, I read the size of the array and initialize it with numbers read

13条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 08:18

    public class DuplicationNoInArray {
    
        /**
         * @param args
         *            the command line arguments
         */
        public static void main(String[] args) throws Exception {
            int[] arr = { 1, 2, 3, 4, 5, 1, 2, 8 };
            int[] result = new int[10];
            int counter = 0, count = 0;
            for (int i = 0; i < arr.length; i++) {
                boolean isDistinct = false;
                for (int j = 0; j < i; j++) {
                    if (arr[i] == arr[j]) {
                        isDistinct = true;
                        break;
                    }
                }
                if (!isDistinct) {
                    result[counter++] = arr[i];
                }
            }
            for (int i = 0; i < counter; i++) {
                count = 0;
                for (int j = 0; j < arr.length; j++) {
                    if (result[i] == arr[j]) {
                        count++;
                    }
    
                }
                System.out.println(result[i] + " = " + count);
    
            }
        }
    }
    

提交回复
热议问题