微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我需要帮助优化上个月面试时问到的一个数组问题

如何解决我需要帮助优化上个月面试时问到的一个数组问题

给定2个数组a和b,求b[i] + b[j] + b[k]的最大值 (i !=j != k) ,满足以下条件 a[i] > a[j] > a[k]

我可以使用 3 个循环来计算它。我在面试中被要求优化问题,但无法做到。 有没有比 O(n^3) 更好的优化方法? 谢谢

解决方法

通过对 B(n log n 时间)进行排序并跟踪使用了哪些索引,检查 A 的属性 {{1} }.请注意,由于 i、j 和 k 之间的唯一关系是它们不相等,因此它们的顺序似乎无关紧要。 (另外,可能 i 和 k 可以相等,但我们现在将忽略这一点。)

伪代码:

A[i] > A[j] > A[k]

这取决于这样一个事实:如果您对数组(例如 function findSum(A,B): declare array B_with_index // O(n) for index 0 to |B|-1: insert (B[index],index) into B_with_index // O(n log n) sort B_with_index by its first value,descending // O(n) for index 0 to |B|-3: b_1 := B_with_index[index] b_2 := B_with_index[index+1] b_3 := B_with_index[index+2] // Note that we're only checking for inequality here // This is because i,j and k have no relationship // other than inequality. E.q.,if A[i] < A[j],we can // just swap the definitions of i and j. if A[b_1.index] != A[b_2.index] and A[b_2.index] != A[b_3.index] then return b_1.value + b_2.value + b_3.value return error )进行排序,则最大总和将位于开头:[1,5,25,2,-5,50]。然后您所要做的就是确保所涉及的索引在 [50,1,-5] 中具有正确的属性。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。