?LeetCode刷題實戰(zhàn)88:合并兩個有序數(shù)組
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做?合并兩個有序數(shù)組,我們先來看題面:
https://leetcode-cn.com/problems/merge-sorted-array/
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 equal to m + n) to hold additional elements from nums2.
題意
輸入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
輸出:[1,2,2,3,5,6]
解題
class?Solution?{
??public?void?merge(int[] nums1, int?m, int[] nums2, int?n)?{
????System.arraycopy(nums2, 0, nums1, m, n);
????Arrays.sort(nums1);
??}
}

class?Solution?{
??public?void?merge(int[] nums1, int?m, int[] nums2, int?n)?{
????// Make a copy of nums1.
????int?[] nums1_copy = new?int[m];
????System.arraycopy(nums1, 0, nums1_copy, 0, m);
????// Two get pointers for nums1_copy and nums2.
????int?p1 = 0;
????int?p2 = 0;
????// Set pointer for nums1
????int?p = 0;
????// Compare elements from nums1_copy and nums2
????// and add the smallest one into nums1.
????while?((p1 < m) && (p2 < n))
??????nums1[p++] = (nums1_copy[p1] < nums2[p2]) ? nums1_copy[p1++] : nums2[p2++];
????// if there are still elements to add
????if?(p1 < m)
??????System.arraycopy(nums1_copy, p1, nums1, p1 + p2, m + n - p1 - p2);
????if?(p2 < n)
??????System.arraycopy(nums2, p2, nums1, p1 + p2, m + n - p1 - p2);
??}
}
上期推文:
