Mauricio - 1 year ago 157
Java Question

What's the meaning of b[a[i] - 1]++?

I just found a piece of code that i don't understand.

``````b[a[i] - 1]++;
``````

this is the context.

``````int firstDuplicate(int[] a) {
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[a[i] - 1]++;
if (b[a[i] - 1] > 1) {
return a[i];
}
}
return -1;
}
``````

The array is

``````int test[] = {2, 3, 3, 1, 5, 2};
``````

Can please someone explain it to me?

`a[]` is an array of Integers.

`b[a[i]]` means in array `b` at index `a[i]`.

e.g.

``````a[] = {1, 2, 3} & b[] = {10, 20, 30}
``````

Here, `b[a[0]]` will give you `20` because `a[0]` returns `1` and `b[1]` is `20`.

In your code it is `b[a[i] - 1]++` which is equivalent to `b[a[i] - 1] = b[a[i] - 1] + 1`

Taking from my e.g. if `i = 0`

`b[a[0] - 1]` will give you `10` as output.

And moreover `b[a[0] - 1]++` will modify the value at `b[0]` to `11`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download