首页 > 代码库 > CC150 9.1
CC150 9.1
9.1 You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.
Option 1.
Create an extra big array C.
iterate both A and B.
return C.
O(m + n)
Option 2.
Assume A is big enough.
Iterate A and B starting from end.
Put max value to the end of A.
int[] merge (int[] a, int[] b, int i) { // assume a[x] has value when x <= i; // And a.length = b.length + i; int m = b.length - 1; int n = i; int k = a.length - 1; for ( k >= 0 ) { if (m < 0) { a[k] = b[n]; n --; } else if (n < 0) { a[k] = a[m]; m --; } else if (a[m] >= b[n]) { a[k] = a[m]; m --; } else { a[k] = b[n]; n --; } k --; } }
CC150 9.1
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。