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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值