88:合并两个有序数组

This commit is contained in:
huangge1199@hotmail.com 2021-04-06 12:33:19 +08:00
parent 9d91c4137e
commit 46756d2874
2 changed files with 111 additions and 0 deletions

View File

@ -0,0 +1,79 @@
//给你两个有序整数数组 nums1 nums2请你将 nums2 合并到 nums1 使 nums1 成为一个有序数组
//
// 初始化 nums1 nums2 的元素数量分别为 m n 你可以假设 nums1 的空间大小等于 m + n这样它就有足够的空间保存来自 nu
//ms2 的元素
//
//
//
// 示例 1
//
//
//输入nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
//输出[1,2,2,3,5,6]
//
//
// 示例 2
//
//
//输入nums1 = [1], m = 1, nums2 = [], n = 0
//输出[1]
//
//
//
//
// 提示
//
//
// nums1.length == m + n
// nums2.length == n
// 0 <= m, n <= 200
// 1 <= m + n <= 200
// -109 <= nums1[i], nums2[i] <= 109
//
// Related Topics 数组 双指针
// 👍 880 👎 0
package leetcode.editor.cn;
//88:合并两个有序数组
public class MergeSortedArray {
public static void main(String[] args) {
//测试代码
Solution solution = new MergeSortedArray().new Solution();
int[] nums1 = new int[]{1, 2, 3, 0, 0, 0};
int[] nums2 = new int[]{2, 5, 6};
solution.merge(nums1, 3, nums2, 3);
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i = 0, j = 0;
if (m == 0) {
nums1 = nums2;
return;
}
if (n == 0) {
return;
}
while (j < n) {
if (i >= m) {
nums1[i] = nums2[j];
j++;
} else if (nums1[i] > nums2[j]) {
if (m - i - i >= 0) {
if (m + n - 1 - i - i >= 0) {
System.arraycopy(nums1, i, nums1, i + 1, m + n - 1 - i - i);
}
}
nums1[i] = nums2[j];
j++;
}
i++;
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,32 @@
<p>给你两个有序整数数组 <code>nums1</code><em> </em><code>nums2</code>,请你将 <code>nums2</code><em> </em>合并到 <code>nums1</code><em> </em><em></em>使 <code>nums1</code><em> </em>成为一个有序数组。</p>
<p>初始化 <code>nums1</code><code>nums2</code> 的元素数量分别为 <code>m</code><code>n</code><em> </em>。你可以假设 <code>nums1</code><em> </em>的空间大小等于 <code>m + n</code>,这样它就有足够的空间保存来自 <code>nums2</code> 的元素。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
<strong>输出:</strong>[1,2,2,3,5,6]
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>nums1 = [1], m = 1, nums2 = [], n = 0
<strong>输出:</strong>[1]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>nums1.length == m + n</code></li>
<li><code>nums2.length == n</code></li>
<li><code>0 <= m, n <= 200</code></li>
<li><code>1 <= m + n <= 200</code></li>
<li><code>-10<sup>9</sup> <= nums1[i], nums2[i] <= 10<sup>9</sup></code></li>
</ul>
<div><div>Related Topics</div><div><li>数组</li><li>双指针</li></div></div>\n<div><li>👍 880</li><li>👎 0</li></div>