Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6da1672

Browse files
merge-sorted-array
1 parent 7de035b commit 6da1672

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

‎Two-pointers/mergesortedarray.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"Leetcode- https://leetcode.com/problems/merge-sorted-array/ "
2+
'''
3+
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
4+
5+
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
6+
7+
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.
8+
9+
Example 1:
10+
11+
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
12+
Output: [1,2,2,3,5,6]
13+
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
14+
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
15+
'''
16+
def merge(self, nums1, m, nums2, n):
17+
i = 0
18+
j = 0
19+
ans = []
20+
while j < n:
21+
ans.append(nums2[j])
22+
j += 1
23+
while i < m:
24+
ans.append(nums1[i])
25+
i += 1
26+
ans = sorted(ans)
27+
nums1[:] = ans

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /