Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
1 class Solution { 2 public: 3 void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { 4 int i = 0; 5 int j = 0; 6 vector<int> vet; 7 while (i <= m-1&&j <= n-1) 8 { 9 if (nums1[i] < nums2[j]) 10 { 11 vet.push_back(nums1[i]); 12 i++; 13 } 14 else 15 { 16 if (nums1[i] == nums2[j]) 17 { 18 vet.push_back(nums1[i]); 19 vet.push_back(nums2[j]); 20 i++; 21 j++; 22 } 23 else 24 { 25 vet.push_back(nums2[j]); 26 j++; 27 } 28 } 29 } 30 while (i <= m-1) 31 { 32 vet.push_back(nums1[i]); 33 i++; 34 } 35 while (j <= n-1) 36 { 37 vet.push_back(nums2[j]); 38 j++; 39 } 40 nums1 = vet; 41 } 42 };
1 class Solution { 2 public: 3 void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { 4 5 int curr = m+n-1, idx1 = m-1, idx2 = n-1; 6 while (idx1 >= 0 || idx2 >= 0){ 7 if (idx1 >= 0 && idx2 >= 0){ 8 if (nums1[idx1] < nums2[idx2]) 9 nums1[curr--] = nums2[idx2--]; 10 else 11 nums1[curr--] = nums1[idx1--]; 12 } 13 else if (idx1 < 0) 14 nums1[curr--] = nums2[idx2--]; 15 else 16 nums1[curr--] = nums1[idx1--]; 17 } 18 } 19 };