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 nums1and nums2 are m and n respectively.
Tags: Array Two Pointers
//询问:是否有错误输入?即是否确定是已排序的,是否需要自己检测
//询问:是升序还是降序
//第一次做的时候,居然卡住了,别慌,很简单的
注意:本题与归并排序中的合并有序数组和合并有序单链表的区别!!
1 #include "stdafx.h" 2 #include <iostream> 3 using namespace std; 4 class Solution 5 { 6 public: 7 void merge(int A[], int m, int B[], int n) 8 { 9 if(m < 0 || n < 0) 10 { 11 return; 12 } 13 14 int indexA=m-1; 15 int indexB=n-1; 16 int indexCurrent = m+n-1; 17 //假设排序是升序排列的 18 //假设是排序的!! 19 //题意:将B插入A中,故从后往前找【题意理解清楚!!】 20 while(indexB >= 0 && indexCurrent>=0) //仍有需要插入的数据 21 { 22 if(indexA < 0) 23 break; 24 if(A[indexA] >=B [indexB]) 25 A[indexCurrent--] = A[indexA--]; 26 else 27 A[indexCurrent--] = B[indexB--]; 28 } 29 //!!!之前忘记了//与合并有序链表的区别 30 while(indexB >= 0) 31 { 32 A[indexCurrent--] = B[indexB--]; 33 } 34 } 35 }; 36 int main() 37 { 38 Solution sol; 39 //测试1:a空 40 int a1[10];//特殊情况:a[] 41 int b1[4]= {1,3,5,6}; 42 sol.merge(a1,0,b1,4); 43 for(auto p : a1) 44 cout << p << " "; 45 cout << endl; 46 //测试2:a长,b短 47 int a2[10]= {0,1,4,7}; 48 int b2[3]= {3,5,6}; 49 sol.merge(a2,4,b2,3); 50 for(auto p : a2) 51 cout << p << " "; 52 cout << endl; 53 //测试3:a短,b长 54 int a3[10]= {0,1,2}; 55 int b3[4]= {3,4,4,6}; 56 sol.merge(a3,3,b3,4); 57 for(auto p : a3) 58 cout << p << " "; 59 cout << endl; 60 return 0; 61 }
时间: 2024-10-07 16:58:29