Skip to content

Instantly share code, notes, and snippets.

@c02y
Created May 14, 2020 22:26
Show Gist options
  • Save c02y/a421ffbec3fa048f1be714abf35f3281 to your computer and use it in GitHub Desktop.
Save c02y/a421ffbec3fa048f1be714abf35f3281 to your computer and use it in GitHub Desktop.
MergeSortedArray.py
# 88. Merge Sorted Array (Easy)
# https://leetcode-cn.com/problems/merge-sorted-array/description/
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
last = m + n - 1
while n:
if m == 0 or nums1[m - 1] <= nums2[n - 1]:
n = n - 1
nums1[last] = nums2[n]
else:
m = m - 1
nums1[last] = nums1[m]
last = last - 1
if __name__ == '__main__':
nums1 = [1, 2, 3, 0, 0, 0]
nums2 = [2, 5, 6]
Solution().merge(nums1, 3, nums2, 3)
print(nums1)
@c02y
Copy link
Author

c02y commented May 14, 2020

Cpp version:

// 88. Merge Sorted Array (Easy)
// https://leetcode-cn.com/problems/merge-sorted-array/description/
#include <iostream>
#include <vector>

class Solution {
public:
	void merge(std::vector<int>& nums1, int m, std::vector<int>& nums2, int n) {
		int last = m + n -1;
		while (n) {
			if(m == 0 || nums1[m - 1] <= nums2[n - 1]) {
				nums1[last--] = nums2[--n];
			} else {
				nums1[last--] = nums1[--m];
			}
		}
	}
};

int main()
{
	std::vector<int> nums1{1, 2, 3, 0, 0, 0};
	std::vector<int> nums2{2, 5, 6};

	Solution().merge(nums1, 3, nums2, 3);
	for (auto i : nums1)
		std::cout << i << " " << std::endl;

	return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment