HackerRank-Medium筆記(三)


Absolute Permutation(絕對置換)

Problem Link

Problem Description

額外寫了一個(gè)swap方法用于交換數(shù)組中的兩個(gè)元素
2*k為一組進(jìn)行兩兩交換,故長度n需為2k的倍數(shù)

Function Description

Complete the absolutePermutation function in the editor below. It should return an integer that represents the smallest lexicographically smallest permutation, or -1 if there is none.
absolutePermutation has the following parameter(s):

  • n: the upper bound of natural numbers to consider, inclusive
  • k: the integer difference between each element and its index
Solution
def swap(arr, i, j):
    temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
    return arr

def absolutePermutation(n, k):
    count = list(range(1, n+1))
    index = list(range(1, n+1))

    if k == 0 :
        return index
    if (k != 0 and n % 2 != 0) or (2 * k > n) or (n % (2 * k) != 0):
        return [-1]

    for i in range(n):
        for j in range(i+1, n):
            if index[i] in count and index[i] + k == index[j]:
                index = swap(index, i, j)
                count.remove(index[i])
                count.remove(index[j])
    if not count:
        return index
    else:
        return [-1]

這種寫法總是有一半的testcase會出現(xiàn)timeout,參考討論區(qū)的提示改寫為以下的版本后全部testcase順利通過

def absolutePermutation(n, k):
    index = list(range(1, n + 1))

    if k == 0:
        return index
    if (k != 0 and n % 2 != 0) or (2 * k > n) or (n % (2 * k) != 0):
        return [-1]
    
    group = n // (2 * k)
    for i in range(group):
        ind = i*2*k
        for j in range(k):
            index = swap(index, ind+j, ind+j+k)
    return index

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容