I want to know that why there is no error in this code when I run it, especially in this line ret[(int) b[i]] = p;. Actually this solution I found in leetcode contest 387, user who got rank 3.
public int[] shrink(int[] a) {
int n = a.length;
long[] b = new long[n];
for (int i = 0; i < n; i++) b[i] = (long) a[i] << 32 | i;
Arrays.sort(b);
int[] ret = new int[n];
int p = 0;
for (int i = 0; i < n; i++) {
if (i > 0 && (b[i] ^ b[i - 1]) >> 32 != 0) p++;
ret[(int) b[i]] = p;
}
return ret;
}
Explain this line ret[(int) b[i]] = p; why there is no overflow.
According to §5.1.3. Narrowing Primitive Conversion:
That method is using a long to represent two integers, and casting the
longto anintwill retrieve the least significant 32 bits (which is the index in the original array).