Professional Documents
Culture Documents
7 Suppose you are given an integer c and an array, A, indexed from 1 to n, of n integers in the range from 1 to 5n (possibly
with duplicates). Describe an efficient algorithm for determining if there are two integers, A[i] and A[j], in A that sum to c. that is,
such that c = A[i]+ A[j], for 1 <= i < j <= n. What is the running time of your algorithm?
Algorithn comtcn วะ
Inpvt An A
storing integers
ะ
n ≥ 1
array
Display the
Outpt ะ
integer
COU ท -
for i ←
o
to n -
า do
tor to do
j
← im
j < n
if c Aci ] *
Acj ] > Aci ] +
Acj ]
covn
- count +1
return count
i.
The
running
time of the algorithm is Ocn )
F-
#
Outpt ะ 3
Algorithm array
Reverse (A) ะ
Input ะ
An n
-
element array Aof
integers
of A
Output ะ
Reverse Array
start ←
o
end ←
nn
temp ← Acstarts
A [ starts ← A [ end ]
A [ ends ←
temp
start ← start + า
end ← end -
า
return start
i.
The
running
time of the algorithm is Ocn )
F- .
Convertcs )
AI gorithm ะ
Inputi An n
-
element array S of
string
Output ะ
←
num o
for i ← ◦ to nn do
← * + C 5 [ I ] -0 )
num nvm 1o
return num
'
i.
The
running
time of the algorithm is Ocn )
F-
¥
Input
" "
:
{ 123 }
Output ะ
123
Output ะ
the longest sorted subarrays of A
max ←
1
len ←
1
for i ←
า to m do
len ← len +1
else
max ← len
Ien ←
1
return max
i.
The
running
time of the algorithm is Ocn )
E-
±
Input [] { 5,6
ะ
3,5 7,8 9 1,2 }
=
arr
, , , ,
Output ะ
5
Inpvt ะ
An n
-
element array
A of
positive integers
the outlier valuex
Output ะ
value ←
o
for i ← ◦ to n do
valve ←
value ^ Aci ]
return value
i.
The
running
time of the algorithm is 0 (1)
5
¥ -
Input ะ
A [] =
{ 7,3 5. 4,5 ,
,
3,4 ]
Output ะ 7
res =
7 n (3 ^ 3) n (4 ^ 4) ^ (5^5)
=
7 n 0 ^ 0 ^ 0