Given two sorted integer arrays nums1
and nums2
, merge nums2
into nums1
as one sorted array.
The number of elements initialized in nums1
and nums2
are n and m respectively. You may assume that nums1
has enough space (size that is equal to m + n
) to hold additional elements from nums2
.
Example 1:
Input: nums1 = [1,2,3,0,0,0], n = 3, nums2 = [2,5,6], m = 3 Output: [1,2,2,3,5,6]
Approach
Java
import java.util.Arrays;public class MergeArray {public static void main(String[] args) {int nums1[] = { 1,2,3,0,0,0 };int n = 3;int nums2[] = { 2,5,6 };int m = 3;merge(nums1, n, nums2, m);System.out.println(Arrays.toString(nums1));}// method for merge two sorted arraypublic static void merge(int[] nums1, int n, int[] nums2, int m) {int i = nums1.length - 1;n = n - 1;m = m - 1;// iterate till n>0 and m>0while (n >= 0 && m >= 0) {// set element at last of arrayif (nums1[n] > nums2[m]) {nums1[i--] = nums1[n];n--;} else {nums1[i--] = nums2[m];m--;}}while (n >= 0) {nums1[i--] = nums1[n];n--;}while (m >= 0) {nums1[i--] = nums2[m];m--;}}}
C++
#include <bits/stdc++.h>using namespace std;//function to merge two sorted arrayvoid merge(vector<int> &nums1, int n, vector<int> &nums2, int m){int i = nums1.size() - 1;n = n - 1;m = m - 1;// iterate till n>=0 and m>=0while (n >= 0 && m >= 0){// set element at last of arrayif (nums1[n] > nums2[m]) {nums1[i--] = nums1[n];n--;} else {nums1[i--] = nums2[m];m--;}}//if first array is leftwhile (n >= 0) {nums1[i--] = nums1[n];n--;}//if second array is leftwhile (m >= 0) {nums1[i--] = nums2[m];m--;}}int main(){vector<int> nums1 = {1,2,3,0,0,0};int n = 3;vector<int> nums2= { 2,5,6 };int m = 3;merge(nums1, n, nums2, m);//print the final arrayfor(int i=0;i<nums1.size();i++)cout<<nums1[i]<<" ";return 0;}
No comments:
Post a Comment