简体   繁体   中英

How to check max number of elements that are spaced evenly?

I have an array and my goal is to find out how many are spaced by multiples of 11. The array is NOT sorted.

Such as [27, 16, 52, 84], this would return 2
        [1, 55, 66, 33] should return 3.
        [99, 8, 52, 32] should return 0

Currently what I have is to basically run through for-each element in the array, check every other element with multiplying by 11. But this leaves me at a O(n²) runtime, anyway I can optimize this?

 static int eval(int [] a) {
       int i, j, k, counter = 0;
       for (i = 0; i < a.length; i++) {
            for (j = 0; j < a.length; j++) {
                if (i != j) {
                   for (k = -9; k < 10; k++) {
                        if (a[i] == a[j] + k*11) {
                            counter++;
                            break;
                        }
                   }
                }
            }
       }
     //if found nothing, will return 0, if found 1 matching, 
     //it should be 2 numbers that share this 11-difference. 
    return counter : counter == 0? 0: counter + 1;
 }

Thanks!

You would need 2 loops to accomplish this. Calculate the difference between every element, and if that number is a multiple of 11, increment the counter. Return half the counter, as if you hit a multiple of 11 between two elements, you will end up hitting the same two elements again later in the loop:

 static int eval(int [] a) {
     int counter = 0;
     for (int i = 0; i < a.length; i++) {
         for (int j = 0; j < a.length; j++) {
             if (i != j && Math.abs(a[i] - a[j]) % 11 == 0) {
                 counter++;
             }
         }
     }
     return counter / 2;
 }

It's not entirely clear what the output is supposed to be for, say, [11, 22, 34, 45] . I'm interpreting the question as asking for the size of the largest subset of the input where all differences between elements of the subset are multiples of 11, and where size-1 subsets don't count.

All inputs with the same residue mod 11 are spaced by multiples of 11, so we only need to count how many ints in the input have each possible value of i % 11 . This takes time linear in the size of the input.

static int eval(int[] a) {
    int[] inputsPerResidue = new int[11];
    for (int i : a) {
        inputsPerResidue[i % 11]++;
    }
    int maxGroupSize = 0;
    for (int groupSize : inputsPerResidue) {
        if (groupSize > 1 && groupSize > maxGroupSize) {
            maxGroupSize = groupSize;
        }
    }
    return maxGroupSize;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM