Re: [問題] 未排序的陣列,演算法相關問題

看板CSSE (電腦科學及軟體工程)作者 (喲)時間14年前 (2010/05/09 10:35), 編輯推噓1(103)
留言4則, 2人參與, 最新討論串4/13 (看更多)
※ 引述《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
X和Y不用sort嗎?
05/09 11:55, 1F

05/09 12:03, , 2F
題目說兩個是unsorted.
05/09 12:03, 2F

05/09 12:04, , 3F
可能做太快了,跳過好幾個case,我再檢查一下.
05/09 12:04, 3F

05/09 12:35, , 4F
喔,類似merge sort是指程式結構類似merge sort,不是真做排序
05/09 12:35, 4F
※ 編輯: yauhh 來自: 218.160.109.216 (05/09 15:56)
文章代碼(AID): #1BvXzh_n (CSSE)
討論串 (同標題文章)
文章代碼(AID): #1BvXzh_n (CSSE)