【发布时间】:2010-05-04 11:11:38
【问题描述】:
我正在寻找解决以下问题的最有效方法
问题:
given an array Before = { 8, 7, 2, 1} and an array After ={1, 3, 8, 8}
find the added and the removed elements
the solution is:
added = 3, 8
removed = 7, 2
到目前为止我的想法是:
for i = 0 .. B.Lenghtt-1
{
for j= 0 .. A.Lenght-1
{
if A[j] == B[i]
A[j] = 0;
B[i] = 0;
break;
}
}
// B elemnts different from 0 are the Removed elements
// A elemnts different from 0 are the Added elemnts
有谁知道更好的解决方案,可能更有效,并且不会覆盖原始数组
【问题讨论】:
-
如果添加 3、8 并删除 7、2、1,则“数组之后”应为
{3, 8, 8}或{1, 3, 8, 8}。 -
“After”数组中不能存在“1”。你从一个“1”开始,你删除它,你不加回来,那为什么它在 After 数组中?你应该修正你的例子。
-
我经常犯的错误,我已经改正了。谢谢,jj
标签: arrays algorithm language-agnostic