Re: [問題] 未排序的陣列,演算法相關問題
※ 引述《mqazz1 (無法顯示)》之銘言:
: given two unsorted arrays X and Y,
: each contains m and n numbers, separately.
: design an algorithm so that,
: given a number d,
: it could determine if there exists two integers i and j,
: such that X[i] + Y[i] = d
: use less than O(m*n) running time
: 我想請問這題大致上從哪方面下手會比較簡易
: 謝謝
類似merge sort
ix_ = 0, iy_ = 0;
if (X[ix_]+Y[iy_] != d) {
ix = 1; iy = 1;
while (ix != length(X) && iy != length(Y)) {
int c;
if (X[ix_]+Y[iy_] < d) {
while (X[ix] <= X[ix_] && ix < length(X)) ix++;
while (Y[iy] <= Y[iy_] && iy < length(Y)) iy++;
c = near(X[ix]-X[ix_], Y[iy]-Y[iy_], d-X[ix_]-Y[iy_]);
// Find which of arg 1 and arg 2 is near arg3
if (c == X[ix]-X[ix_])
ix_ = ix;
else // c == Y[iy]-Y[iy_]
iy_ = iy;
} else { // X[ix_]+Y[iy_] > d
while (X[ix] >= X[ix_] && ix < length(X)) ix++;
while (Y[iy] >= Y[iy_] && iy < length(Y)) iy++;
c = near(X[ix_]-X[ix], Y[iy_]-Y[iy], X[ix_]+Y[iy_]-d);
if (c == X[ix_]-X[ix])
ix_ = ix;
else // c == Y[iy_]-Y[iy]
iy_ = iy;
}
if (X[ix_]+Y[iy_] == d) break;
}
}
if (X[ix_]+Y[iy_] == d)
output(ix_, iy_);
else
echo("No solution");
===============================
___Update 05/09 12:59, 15:55___ 重寫個演算法
ix_ = iy_ = 0 // Treat X[ix_] and Y[iy_] as candidate result
if X[ix_] + Y[iy_] =\= d, do:
ix = iy = 1 // Other records first to be considered
while ix < length of X - 1 and iy < length of Y - 1, do:
Check that it's ix or iy which makes d' nearer to d
than X[ix_]+Y[iy_], where d' may be X[ix]+Y[iy_] or
X[ix_]+Y[iy].
If ix and iy both maks d' nearer to d than ix_ and ix_,
ix_ = ix, iy_ = iy, ix = ix+1, iy = iy+1.
If it's ix that makes d' nearer to d than ix_, ix_ = ix
and then ix = ix+1.
If it's iy that makes d' nearer to d than iy_, iy_ = iy
and then iy = iy+1.
If both ix and iy do not make any d' nearer to d,
ix = ix+1 and iy = iy+1.
if X[ix_] + Y[iy_] = d, result is (ix_, iy_)
otherwise no result
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.160.209.141
推
05/09 11:55, , 1F
05/09 11:55, 1F
→
05/09 12:03, , 2F
05/09 12:03, 2F
→
05/09 12:04, , 3F
05/09 12:04, 3F
→
05/09 12:35, , 4F
05/09 12:35, 4F
※ 編輯: yauhh 來自: 218.160.109.216 (05/09 15:56)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 4 之 13 篇):
CSSE 近期熱門文章
PTT數位生活區 即時熱門文章