Re: Microsoft Interview Question

看板Oversea_Job (海外工作)作者時間17年前 (2008/01/27 16:18), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《Baudelaire.bbs@ptt.cc (Sunnyvale)》之銘言: : ※ 引述《Baudelaire (Sunnyvale)》之銘言: : : 這題據強者我ebay的朋友說,Google在on-campus也問過他這題。 : 算是quicksort裡面的in-place partition,也不會太難。 : public static int Partition(Ball[] aBalls) { : int left = 0, right = aBalls.length - 1; : BallColor pivotColor = aBalls[0].Color(); : while (left <= right) { : BallColor leftColor = aBalls[left].Color(); : BallColor rightColor = aBalls[right].Color(); : if (leftColor == pivotColor) && rightColor == pivotColor) : left++; : } else if (leftColor == pivotColor && rightColor != pivotColor) { : left++; : } else if (leftColor != pivotColor && rightColor != pivotColor) { : right--; : } else if (leftColor != pivotColor && rightColor == pivotColor) { : Ball tmp = aBalls[left]; : aBalls[left] = aBalls[right]; : aBalls[right] = tmp; : left++; right--; : } : } : return left; : } 直接改Cormen那本書裡的partition似乎可以提供更精簡的答案 請參考 Partition(Ball A[]) { i = -1; k = A.length - 1; x = A[k]; Ball temp; for(j=0; j < k; ++j) { if(A[j] != x) // Here is the key modification. { ++i; temp = A[i]; A[i] = A[j]; A[j] = temp; } } return (i+1); } -- ※ 發信站: 批踢踢參(ptt3.cc) ◆ From: 168.7.230.23
文章代碼(AID): #17d3vS00 (Oversea_Job)
文章代碼(AID): #17d3vS00 (Oversea_Job)