You are given two integer arrays
nums1
andnums2
, sorted in non-decreasing order, and two integersm
andn
, representing the number of elements innums1
andnums2
respectively.Merge
nums1
andnums2
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 ofm + n
, where the firstm
elements denote the elements that should be merged, and the lastn
elements are set to0
and should be ignored.nums2
has a length ofn
.给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。
请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。
注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.Example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0 Output: [1] Explanation: The arrays we are merging are [1] and []. The result of the merge is [1].Example 3:
Input: nums1 = [0], m = 0, nums2 = [1], n = 1 Output: [1] Explanation: The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
一些生词:
respectively
英 [rɪˈspektɪvli] 美 [rɪˈspektɪvli]
adv.
分别地;分别;各自;顺序为;依次为merge
英 [mɜːdʒ] 美 [mɜːrdʒ]
v.
合并;融入;(使)结合;并入;相融;渐渐消失在某物中store
英 [stɔː(r)] 美 [stɔːr]
n.
(大型)百货商店;商店;店铺;贮存物;备用物
vt.
贮存;贮藏;保存;(在计算机里)存储;记忆accommodate
英 [əˈkɒmədeɪt] 美 [əˈkɑːmədeɪt]
v.
容纳;为(某人)提供住宿(或膳宿、座位等);为…提供空间;考虑到;顾及denote
英 [dɪˈnəʊt] 美 [dɪˈnoʊt]
vt.
标志;预示;象征;表示;意指donate
英 [dəʊˈneɪt] 美 [ˈdoʊneɪt]
vt.
捐赠;(尤指向慈善机构)赠送;献(血);捐献(器官)
这题很简单,注意最后要求nums1数组返回
直接看代码吧
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
// int[] array = new int[m + n];
// for(int i = 0;i < m;i++){
// array[i] = nums1[i];
// }
for(int i = 0;i < n;i++){
nums1[m + i] = nums2[i];
}
Arrays.sort(nums1);
}
}
补充一个知识点吧,在java中常见的数组拷贝有
System.arraycopy()和Arrays.copyOf()方法。
.arraycopy底层是native进行修饰,大家就不用关心了
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
大家可以看到,Arrays.copyOf()底层也是调用的System.arraycopy()
public static T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
public static T[] copyOf(U[] original, int newLength, Class extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}