题目:
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
说明:无
实现:
精简实现:
1 // 时间复杂度 O(m+n),空间复杂度 O(1) 2 class Solution { 3 public: 4 void merge(int A[], int m, int B[], int n) { 5 int i=m-1,j=n-1,k=m+n-1; 6 while(i>=0&&j>=0)//从后面开始比较归并,直到有一个数组归并完 7 { 8 A[k--]=A[i]>B[j]?A[i--]:B[j--];//将大数赋给A[k] 9 } 10 while(j>=0)//若B还没归并完,直接归并到A 11 A[k--]=B[j--]; 12 } 13 };
leetcode 题解:Merge Sorted Array(两个已排序数组归并)
时间: 2024-11-03 16:53:37