G'day Monks,
Why do you think someone would call the following a 'naive' solution?
Create sublists from an array of integers ,in increasing order:
Input: [ 1,2,3,4,5,6,7,8,3,5,6,3,8,1,7,8 ]
Desired Output: [[ 1, 2, 3, 4, 5, 6, 7, 8 ], [ 3, 5, 6 ], [ 3, 8], [ 1,7,8]]
my @array1 = (1,2,3,4,5,6,7,8,3,5,6,3,8,1,7,8);
my @newarray;
my @tmparray;
for (0..$#array1)
{
if ($_> 0 && $array1[$_] < $array1[$_-1])
{
push (@newarray, [@tmparray]);
undef(@tmparray);
}
push (@tmparray, $array1[$_]);
}
push (@newarray, [@tmparray]) if defined @tmparray;
Then from the output generated sort items in a single array:
My assumption was that I no longer had @array1 to work with and had to create the final sorted array from @newarray.
Input: [[ 1, 2, 3, 4, 5, 6, 7, 8 ], [ 3, 5, 6 ], [ 3, 8 ]]
Desired Output [ 1,1,2,3,3,3,4,5,5,6,6,7,7,8,8,8 ]
my @array3;
for (@newarray)
{
push @array3, @$_;
}
@array3 = sort @array3;
Also, is this wrong to say in this particular case the complexity is O(n) disregarding the complexity of sort?
FYI: This was in an interview...
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.