Skip to content

Commit

Permalink
Update 88.merge-sorted-array.md
Browse files Browse the repository at this point in the history
  • Loading branch information
azl397985856 authored Mar 2, 2020
1 parent 37485d9 commit f9e7d1f
Showing 1 changed file with 24 additions and 53 deletions.
77 changes: 24 additions & 53 deletions problems/88.merge-sorted-array.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
## 题目地址

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

## 题目描述

```
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
给定两个有序整数数组 nums1 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
Note:
说明:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
初始化 nums1 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
Input:
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
输出: [1,2,2,3,5,6]
```

## 思路
Expand Down Expand Up @@ -102,50 +102,12 @@ function merge(nums1, nums2) {

## 代码

代码支持:Python3, C++, JavaScript


JavaSCript Code:

```js
/*
* @lc app=leetcode id=88 lang=javascript
*
* [88] Merge Sorted Array
*
* https://leetcode.com/problems/merge-sorted-array/description/
*
* algorithms
* Easy (34.95%)
* Total Accepted: 347.5K
* Total Submissions: 984.7K
* Testcase Example: '[1,2,3,0,0,0]\n3\n[2,5,6]\n3'
*
* Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as
* one sorted array.
*
* Note:
*
*
* The number of elements initialized in nums1 and nums2 are m and n
* respectively.
* You may assume that nums1 has enough space (size that is greater or equal to
* m + n) to hold additional elements from nums2.
*
*
* Example:
*
*
* Input:
* nums1 = [1,2,3,0,0,0], m = 3
* nums2 = [2,5,6], n = 3
*
* Output: [1,2,2,3,5,6]
*
*
*/
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
var merge = function(nums1, m, nums2, n) {
// 设置一个指针,指针初始化指向nums1的末尾(根据#62,应该是index为 m+n-1 的位置,因为nums1的长度有可能更长)
// 然后不断左移指针更新元素
Expand Down Expand Up @@ -175,7 +137,7 @@ var merge = function(nums1, m, nums2, n) {
}
};
```
模仿上述代码,思路相同

C++ code:
```
class Solution {
Expand All @@ -199,7 +161,7 @@ public:
};
```

Python 代码
Python Code
```python
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
Expand All @@ -222,3 +184,12 @@ class Solution:
if n > 0:
nums1[:n] = nums2[:n]
```


**复杂度分析**
- 时间复杂度:$O(M + N)$
- 空间复杂度:$O(1)$

欢迎关注我的公众号《脑洞前端》获取更多更新鲜的LeetCode题解

![](https://pic.leetcode-cn.com/89ef69abbf02a2957838499a96ce3fbb26830aae52e3ab90392e328c2670cddc-file_1581478989502)

0 comments on commit f9e7d1f

Please sign in to comment.