如何将两个排序的数组合并到排序的数组?(How to merge two sorted arrays into a sorted array? [closed])

编程入门 行业动态 更新时间:2024-10-26 15:23:20
如何将两个排序的数组合并到排序的数组?(How to merge two sorted arrays into a sorted array? [closed])

这是在采访中被问到我,这是我提供的解决方案:

public static int[] merge(int[] a, int[] b) { int[] answer = new int[a.length + b.length]; int i = 0, j = 0, k = 0; while (i < a.length && j < b.length) { if (a[i] < b[j]) { answer[k] = a[i]; i++; } else { answer[k] = b[j]; j++; } k++; } while (i < a.length) { answer[k] = a[i]; i++; k++; } while (j < b.length) { answer[k] = b[j]; j++; k++; } return answer; }

有没有更有效的方式来做到这一点?

编辑:校正长度方法。

This was asked of me in an interview and this is the solution I provided:

public static int[] merge(int[] a, int[] b) { int[] answer = new int[a.length + b.length]; int i = 0, j = 0, k = 0; while (i < a.length && j < b.length) { if (a[i] < b[j]) { answer[k] = a[i]; i++; } else { answer[k] = b[j]; j++; } k++; } while (i < a.length) { answer[k] = a[i]; i++; k++; } while (j < b.length) { answer[k] = b[j]; j++; k++; } return answer; }

Is there a more efficient way to do this?

Edit: Corrected length methods.

最满意答案

稍微改进,但在主循环之后,当您到达另一个的末尾时,可以使用System.arraycopy复制任何一个输入数组的尾部。 这不会改变您的解决方案的O(n)性能特征。

A minor improvement, but after the main loop, you could use System.arraycopy to copy the tail of either input array when you get to the end of the other. That won't change the O(n) performance characteristics of your solution, though.

更多推荐

本文发布于:2023-07-28 01:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298226.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   数组   如何将   并到   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!