一,题目描述
英文描述
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.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
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.
中文描述
给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。
请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。
注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。
示例与说明
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAnYldHL0FWby9mZvwFN4ETMfdHLkVGepZ2XtxSZ6l2clJ3LcV2Zh1Wa9M3clN2byBXLzN3btgHL9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsQTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5iMyMjM3kTYiBDZjVjNwIWNzYzX4QTOyYDM4IzLcBTMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
链接:https://leetcode.cn/problems/merge-sorted-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二,解题思路
从后向前遍历,选择较大值放在nums1的末尾。。。
确实是easy题,但是思路没转换过来就很难受了
三,AC代码
Java
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int p = m - 1, q = n - 1;
int index = m + n - 1;
while (index >= 0) {
if (p >= 0 && q >= 0) {
if (nums1[p] > nums2[q]) {
nums1[index--] = nums1[p--];
} else {
nums1[index--] = nums2[q--];
}
} else if (p < 0) {
nums1[index--] = nums2[q--];
} else {
// 不需要排序,剩下的元素本就在nums1中
break;
}
}
}
}
四,解题过程
第一搏
第一次做这道题是2020年7月,2022年9月在面试时遇到了这道题目,居然没做出来。
采用的方法是从前往后遍历数组,用index标记遍历的下标,选出nums1和nums2中较小值与nums1中index对应位置调换,调换之后重新排序nums2数组。。。(⓿_⓿)