Skip to content

Instantly share code, notes, and snippets.

@yitonghe00
Last active October 26, 2019 03:04
Show Gist options
  • Save yitonghe00/943e8042fdb394211469439ad36d1976 to your computer and use it in GitHub Desktop.
Save yitonghe00/943e8042fdb394211469439ad36d1976 to your computer and use it in GitHub Desktop.
88. Merge Sorted Array (https://leetcode.com/problems/merge-sorted-array/): Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold …
// Two pointer solution: read/write (end/end) pointer
// Time: O(m + n), 0ms
// Space: O(1), 36.3mb
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
// Two read pointers for nums1 and nums2, and 1 write pointer for nums1
int r1 = m - 1, r2 = n - 1, w = m + n - 1;
while(w >= 0) {
// **: Merge two into one: handle the cases when one of them is out of elements 658 #1.1
if(r2 < 0 || r1 >= 0 && nums1[r1] >= nums2[r2]) {
nums1[w--] = nums1[r1--];
} else {
nums1[w--] = nums2[r2--];
}
}
}
}
// end/end pointers
//********
//<=^ <=^
// i
//*****
// <=^
// j
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment