知之者 不如好之者, 好之者 不如樂之者

기계처럼 살지 말고, 즐기는 인간이 되자

Code/LeetCode

[LeetCode] 88. Merge Sorted Array (Easy/Python)

코방코 2022. 9. 17. 18:20
728x90
 

Merge Sorted Array - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Above is the link to problem.

 

Problem

Two integer arrays nums1 and nums2 which sorted in non-decreasing order are given.

Two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

 

Condition : The final sorted array should not be returned by the function, but instead be stored inside the array nums1.

To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

 

Example 

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3

Output: [1,2,2,3,5,6]

Explanation: The arrays we are merging are [1,2,3] and [2,5,6].

The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.

 

I solved this problem by writing the below code.

 

 

Leave each list with only m and n elements, 

add nums2 elements to nums1 and sort them in non-decreasing order.

 

This code gets the top 88.77% of time efficiency and the top 14.24% of space efficiency.

 

728x90
반응형