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
count ⟵ 0
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]
count ⟵ 0
return mode
Time Complexity: Θ(n^2).
Computing Mode - Presorting
function Mode(A[0..n-1])
Sort(A[0..n-1])
i ⟵ 0
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]
i ⟵ i + runlength
return mode
Time Complexity: O(nlogn).
Sequential Search
function SequentialSearch(A[0..n-1], k)
i ⟵ 0
while A[i] ≠ k and i < n do
i ⟵ i + 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)/2⎦
if 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.