Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public void merge(int[] nums1, int m, int[] nums2, int n) {
- // Checking edge case: if nums2 is empty, we can just return whatever nums1 is, since it's already sorted.
- if (n == 0) {
- return;
- }
- // Checking edge case: if nums1 is empty, we just copy all nums2 values into nums1
- if (m == 0) {
- for(int i = 0; i < n; i++) {
- nums1[i] = nums2[i];
- }
- return;
- }
- // Approach: we're going backwards since we know the end is empty, and the two arrays are already sorted.
- int nums1Index = m-1;
- int nums2Index = n-1;
- int sortedArrayIndex = m + n -1;
- while (nums1Index >= 0 && nums2Index >= 0) {
- if(nums1[nums1Index] < nums2[nums2Index]) {
- nums1[sortedArrayIndex--] = nums2[nums2Index--];
- } else {
- nums1[sortedArrayIndex--] = nums1[nums1Index--];
- }
- }
- // Going through leftover values.
- while (nums1Index >= 0) {
- nums1[sortedArrayIndex--] = nums1[nums1Index--];
- }
- while (nums2Index >= 0) {
- nums1[sortedArrayIndex--] = nums2[nums2Index--];
- }
- }
- }
Add Comment
Please, Sign In to add comment