Re: [問題] array shuffle

看板Programming作者時間18年前 (2007/07/19 02:01), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串4/9 (看更多)
==> FRAXIS.bbs@ptt.cc (喔喔) 提到: > 這是在網路上看到的一個面試問題,不過我一直想不出來解法。 > 給你一個長度為2n的陣列,其中元素為a1, a2, ..., an, b1, b2, ..., bn > 寫一個程式把這個陣列轉換成a1, b1, a2, b2, ..., an, bn > 時間限制是O(n),空間限制是O(1)。 > 我嘗試用in-place rearrangement的方法去做,但是沒辦法成功。 > 有什麼好的辦法嘛? Method 1: Move to a new array Time complexity: O(n) + space complexity: O(n) Method 2: For even number n divide the array into 4 quaters, swap the 2nd and the 3rd quaters Re-divide the swapped array into 2 halfs, recursively do the swap for the first half and the 2nd half. Complexity: O(nlogn) swap. Method 3: tmp <- a <- b <- c <- d <- ...... <- alpha <- beta <- gama <- tmp Similar to method 1, requiring a derived mathematical formula to decide the next position to move. Time complexity: n-1 moves (first and last elements being steady) Space complexity: 1 element space for tmp -- ☆ [Origin:椰林風情] [From: 220-132-95-228.hinet-ip.hin] [Login: **] [Post: 1]

07/19 11:43, , 1F
good
07/19 11:43, 1F
文章代碼(AID): #16dbLX00 (Programming)
文章代碼(AID): #16dbLX00 (Programming)