88. Merge Sorted Array. I think the humbling part is that
- a) I had to do a bunch of googling to find the methods I wanted to use, instead of just knowing them, and
- b) when I got done, I was really happy with my answer. I was using some inbuilt functions from Java, it seemed nice and professional:
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
System.arraycopy(nums2,0,nums1,m,n);
Arrays.sort(nums1);
}
}
And then when I get to the solution page, it gives a performance review that like, “Your solution is better than 35% of other solutions, and it’s memory usage is better than 9% of users.”
Oof.
I guess it’s just a case of keep it simple, stupid. That System.arraycopy() method (that took me that time to hunt down) can just be replaced with a for loop, as long as I’m willing to think out how those indexes move from one to another:
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
for (int i = 0; i < n; i++){
nums1[m+i] = nums2[i];
}
Arrays.sort(nums1);
}
}
This improves the memory usage to a whopping 21% better than other users. Oof.
But wait, then what’s the the point of arraycopy even existing, if the for loop has better memory usage and the execution time is the same? So I build this:
import java.util.Random;
public class Arraycopy_vs_Loop {
static int arraySize = 1000000;
public int[] arraycopy(int intsArray[]) {
long startTime = System.currentTimeMillis();
int copiedArray[] = new int[arraySize];
System.arraycopy(intsArray, 0, copiedArray, 0, arraySize);
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
System.out.println("arraycopy execution Time: " + executionTime + " milliseconds");
return copiedArray;
}
public int[] forLoop(int intsArray[]) {
long startTime = System.currentTimeMillis();
int copiedArray[] = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
copiedArray[i] = intsArray[i];
}
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
System.out.println("loop execution Time: " + executionTime + " milliseconds");
return copiedArray;
}
public static void main(String[] args) {
Random random = new Random();
Arraycopy_vs_Loop avl = new Arraycopy_vs_Loop();
int randomIntsArray[] = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
randomIntsArray[i] = random.nextInt();
}
avl.arraycopy(randomIntsArray);
avl.forLoop(randomIntsArray);
}
}
When arraySize is 10,000, both methods execute in virtually 0 ms, and when arraySize is 100,000, arraycopy still clocks at 0 ms, and the for loop clocks at 2 ms. But when arraysize is 1,000,000 items, arraycopy executes in 3 milliseconds and the loop executes in 12 milliseconds. So arraycopy does have performance advantages when we’re copying a whole bunch of things.
Leave a comment