Transform and Conquer - Instance Simplification

Transform and Conquer - Instance Simplification


原理(Principles)
Try to make the problem easier through some pre-processing, typically sorting. We can pre-sort input to speed up.

Uniqueness Checking - Brute Force

function UniquenessChecking(A[0..n-1])
    for i ⟵ 0 to n-2 do
        for j ⟵ i+1 to n-1 do
            if A[i] = A[j] then
                return false
    return true

Time complexity: Θ(n^2).

Uniqueness Checking - Presorting

function UniquenessChecking(A[0..n-1])
    Sort(A[0..n-1])
    for i ⟵ 0 to n-2 do
        if A[i]=A[i+1] then
            return false
    return true

Time Complexity: O(nlogn). (If we use some algorithms based on key comparison which belong to O(nlogn)).

Mode
A mode is a list or array element which occurs most frequently in the list or array. For example,
42, 78, 13, 13, 57, 42, 57, 78, 13, 98, 42, 33
The element 13 and 43 are modes.

Computing Mode - Brute Force

function mode(A[0..n-1])
    maxfreq ⟵ 0
    count0
    for i ⟵ 0 to n-1 do
        for j ⟵ 0 to n-1 do
            if A[i] = A[j] then
                count++
        if count > maxfreq then
            maxfreq ⟵ count
            mode ⟵ A[i]
        count0
    return mode

Time Complexity: Θ(n^2).

Computing Mode - Presorting

function Mode(A[0..n-1])
    Sort(A[0..n-1])
    i0
    maxfreq ⟵ 0
    while i < n do
        runlength ⟵ 1
        while i + runlength < n and A[i+runlength] = A[i] do
            runlength ⟵ run length + 1
        if runlength > maxfreq then
            maxfreq ⟵ runlength
            mode ⟵ A[i]
        ii + runlength 
    return mode

Time Complexity: O(nlogn).

Sequential Search

function SequentialSearch(A[0..n-1], k)
    i0
    while A[i] ≠ k and i < n do
        ii + 1
    if i=n then
        return -1
    else
        return i

Time Complexity: Θ(n).

Binary Search

function BinarySearch(A[0..n-1],K)
    lo ⟵ 0
    hi ⟵ n-1
    while lo<=hi do
        m ⟵ ⎣(hi+lo)/2if A[m]=K 
            return m
        else if A[m]>K then
            hi ⟵ m-1
        else A[m]<k then 
            lo ⟵ m+1
    return  -1

Time Complexity: Θ(logn).

寫在最後的話(PS)
Transform and conquer is one of algorithmic design techniques. In some case we can use this technique to simplify problems.
Welcome questions always and forever.

發佈了37 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章