When i was doing leetcode 88.merge sorted array, I tried two similar solutions. First solution is correct but the second solution causes array index out of bounds exception.
The difference is (p1 < m && nums1_copy[p1] < nums2[p2])
in the first solution and (nums1_copy[p1] < nums2[p2] && p1 < m)
in the second solution.
What is the reason? I am a beginner in java and I was working with javascript and never faced this issue.
Thanks a lot.
// first solution
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] nums1_copy = new int[m];
int p1 = 0;
int p2 = 0;
for (int i = 0; i < m; i++) {
nums1_copy[i] = nums1[i];
}
for (int i = 0; i < m + n; i++) {
if (p2 >= n || (p1 < m && nums1_copy[p1] < nums2[p2])) {
nums1[i] = nums1_copy[p1++];
} else {
nums1[i] = nums2[p2++];
}
}
}
// second solution
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] nums1_copy = new int[m];
int p1 = 0;
int p2 = 0;
for (int i = 0; i < m; i++) {
nums1_copy[i] = nums1[i];
}
for (int i = 0; i < m + n; i++) {
if (p2 >= n || (nums1_copy[p1] < nums2[p2] && p1 < m)) {
nums1[i] = nums1_copy[p1++];
} else {
nums1[i] = nums2[p2++];
}
}
}