Home [Tail] Merge Sorted Array
Post
Cancel

[Tail] Merge Sorted Array

’ Merge Sorted Array’ in LeetCode (Easy)


📌 Problem

https://leetcode.com/problems/merge-sorted-array/

📌 Answer

The point

  • put data from the last index to first index (descending order)
1
2
3
4
5
6
7
8
9
10
11
class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        
        int tail1 = m - 1, tail2 = n - 1, finished = m + n -1;
        while (tail1 >= 0 && tail2 >= 0)
            nums1[finished--] = nums1[tail1] > nums2[tail2] ? nums1[tail1--] : nums2[tail2--];
        
        while (tail2 >= 0)
            nums1[finished--] = nums2[tail2--];
    }
}
This post is licensed under CC BY 4.0 by the author.

[Easy] Plus One

[Development] CI / CD

Comments powered by Disqus.