Given an array of size N ,we need to find the majority element if it exists ,as efficiently as possible. A majority element in an array of size N is any element which is present more than N/2 times.
Ans
Naive approach:
Just scan the array element wise and then make a count of the frequency of each of the distinct elements present in the array and if any element's count is more than N/2 then it is the majority element, otherwise it doesn't exist!!
One needn't ponder much on the complexity of this bruteforce approach.
This requires O(N) additional space and O(N) time.
Recursive Approach:
Here’s a divide-and-conquer algorithm:
function majority (A[1 . . . N])
if N = 1: return A[1]
let AL , AR be the first and second halves of A
ML = majority(AL ) and MR = majority(AR )
if neither half has a majority:
return ‘‘no majority’’
else:
check whether either ML or MR is a majority element of A
if so, return that element; else return ‘‘no majority’’
Thursday, April 29, 2010
Tuesday, April 27, 2010
Divide a = a1a2 · · · aN by d using long division
Solution
B1 <-- a1 {Bi is what we divide d into in step i}
i <-- 1
while i <= N do
qi <-- largest integer such that d × qi <= Bi; {qi is the ith digit of the quotient q}
if i <= N − 1 then
Bi+1 <-- 10 × (Bi − d × qi) + ai+1
end if
i <-- i + 1;
end while
r <-- BN − d × qN {r is the remainder}
B1 <-- a1 {Bi is what we divide d into in step i}
i <-- 1
while i <= N do
qi <-- largest integer such that d × qi <= Bi; {qi is the ith digit of the quotient q}
if i <= N − 1 then
Bi+1 <-- 10 × (Bi − d × qi) + ai+1
end if
i <-- i + 1;
end while
r <-- BN − d × qN {r is the remainder}
Algorithm Sum N numbers in a list (or array) named values
Solution
sum <-- 0;
index <-- 1;
while index <= N do
sum <-- sum + values[index ];
index <-- index + 1;
end while
print sum;
sum <-- 0;
index <-- 1;
while index <= N do
sum <-- sum + values[index ];
index <-- index + 1;
end while
print sum;
Subscribe to:
Posts (Atom)
