Wanted big God solve codility on two test questions, intelligence and ability big test! (I've been hit hard, see how the Gods are)

Source: Internet
Author: User
Do not say, have the opportunity to do on the codility two test questions, with PHP solution. I wrote two programs that felt good at the time, but came out with a 200 score of 50 points. Wanted God to point out the mistakes in my program, and the solution of the great gods.
Don't say anything, first on the topic:
1. You is given a non-empty zero-indexed array a consisting of N integers. Each element of the array A can be? 1, 0 or 1.

A pair of integers (P, Q), such that 0≤p≤q < N, is called a slice of array a. The sum of a slice (P, Q) is the total of a[p] + a[p + 1] + ... + a[q].

You are given integer S. The goal is to find the largest slice whose sum equals S.

For example, consider integer S = 2 and array A such that:

A[0] = 1
A[1] = 0
A[2] = 1
A[3] = 1
A[4] = 1
A[5] = 1
A[6] = 1
There is exactly the slices (0, 4) and (3, 4) whose sum equals 2. The largest such slice is (0, 4) and its length equals 5.

Write a function:

function solution ($A, $S);

That is, given a non-empty zero-indexed array a consisting of N integers and an integer S, returns the length of the largest Slice whose sum equals S.

The function should return? 1 if there is no such slice.

For example, given S = 2 and:

A[0] = 1
A[1] = 0
A[2] = 1
A[3] = 1
A[4] = 1
A[5] = 1
A[6] = 1
The function should return 5, as explained above.

Assume that:

N and S are integers within the range [1..100,000];
Each element of array A was an integer within the range [? 1..1].
Complexity:

Expected worst-case time complexity is O (N);
Expected worst-case space complexity is O (N), beyond input storage (not counting the storage required for input arguments) .
Elements of input arrays can be modified.


2.A non-empty zero-indexed Array A consisting of N integers is given.

You can perform a single swap operation in array a. This operation takes II indices I and J, such that 0≤i≤j < N, and exchanges the values of a[i] and a[j].

The goal is to check whether array A can be sorted into non-decreasing order by performing only one swap operation.

For example, consider array A such that:

A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 3
A[4] = 7
After exchanging the values a[2] and a[3] we obtain an array [1, 3, 3, 5, 7], which are sorted in non-decreasing order.

Write a function:

function solution ($A);

That, given a non-empty zero-indexed array a consisting of N integers, returns true if the array can is sorted into non-de Creasing ORDER by one swap operation or false otherwise.

For example, given:

A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 3
A[4] = 7
The function should return true, as explained above.

On the other hand, for the following array:

A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 3
A[4] = 4
The function should return false, as there is no single swap operation that sorts the array.

Assume that:

N is an integer within the range [1..100,000];
Each element of within the range [1..1,000,000,000].
Complexity:

Expected worst-case time complexity is O (N*log (N));
Expected worst-case space complexity is O (N), beyond input storage (not counting the storage required for input arguments) .
Elements of input arrays can be modified.


My program:
For the first question:
function solution ($A, $S) {    //write your code in PHP5.3        $len = count ($A);    $slice =-1;            for ($begin =0; $begin < $len; $begin + +)    {        $total = 0;        for ($end = $begin; $end < $len; $end + +)        {            $total = $total + $A [$end];            if ($total = = $S)            {                $temp = $end-$begin +1;                if ($temp > $slice)                {                    $slice = $temp;                }    }} return $slice;}


For the second question:
function solution ($A) {    //write your code in PHP5.3    $arr = Array ();    $len = count ($A);    $check = false;        for ($i =0; $i < $len-1; $i + +)    {        $arr = $A;        for ($j = $i +1; $j < $len; $j + +)        {            $temp = $arr [$j];            $arr [$j] = $arr [$i];            $arr [$i] = $temp;                        $no _decrease = true;            for ($k =1; $k < $len; $k + +)            {                if ($arr [$k]< $arr [$k-1])                {                    $no _decrease = false;                }            }                        if ($no _decrease = = True)            {                $check = true;}}    }        return $check;   }


I was hit hard, the last 200 points only scored 50 points. How many points can you get, great gods?


Reply to discussion (solution)

Take a look, the second question my program has a clear error, $arr = $A; should be placed after the second for.
Dizzy death.

Don't know English. 0 min

Day Huitie to get 10 points available

Is there no great God to solve? Especially the second problem, it is quite difficult.

Look at the second question first.
The original code calculated the result is correct, and the # # supplement is wrong!
If the $arr = $A; Put it behind the second for. A series of warnings that use undefined variables will appear
Answer is deducted because your answer is not: Time complexity O (N*log (N)) requirements

Can write like this

Var_dump (Solution ([1,3,5,3,7])), Var_dump (solution ([1,3,5,3,4])), function solution ($A) {  $arr = array ();  $len = count ($A);  $check = 0;       for ($i =0; $i < $len-1; $i + +) {    if ($A [$i +1] < $A [$i]) {      $temp = $A [$i +1];      $A [$i +1] = $A [$i];      $A [$i] = $temp;      if ($i > 0 && $A [$i-1] <= $A [$i]) $check + +;    }  }       return $check = = 1;}
BOOL (TRUE) bool (false)

Look at the first question again.
The same results are not errors, but the algorithm does not conform to: the time complexity of O (N) requirements
You use a double loop, so the time complexity is O (n*n)
You can use closures to remove a heavy loop.

Var_dump (Solution ([1,0,-1,1,1,-1,-1], 2)), function solution ($A, $S) {  $len = count ($A);  $slice =-1;           for ($begin =0; $begin < $len; $begin + +) {    $total = 0;    Array_walk ($A, function ($v, $end, $S) use ($begin, & $slice, & $total) {      if ($end < $begin) return;      $total + = $v;      if ($total = = $S) {        $temp = $end-$begin + 1;        if ($temp > $slice) $slice = $temp;      }}    , $S);  }  return $slice;}

Thank you for coming to the moderator.
But for the second question, I have different views:
1. Your idea is: Check the adjacent two size, if the right side of the value less than the left, then swap, and this exchange satisfies I left the size relationship, then check++.
In fact, I thought about this idea when I was doing the problem, but consider this example: 1,6,3,4,3,7. As long as the 6 and the second 3 exchange, you can satisfy the non-descending sequence, and finally should be true. However, according to your algorithm, this topic returns FALSE.

The key point is: The exchange of numbers can be a very clever exchange.

2. In the second question, $arr = $A; should be placed after the second for, I have verified again, there will be no undefined object and other errors. The result is correct.
My idea is to assign a value of $ A to $arr each time, and use the poor lifting method to replace any two different numbers once, judging the result of the exchange is not a non-descending sequence. Yes, returns True, no, and does not change the value of the check to false. As long as the exhaustive method can be done at any one time, the check value becomes true.

This idea is correct, but the complexity of time is not satisfied, deducted points.

Moderator, what do you think?


Look at the second question first.
The original code calculated the result is correct, and the # # supplement is wrong!
If the $arr = $A; Put it behind the second for. A series of warnings that use undefined variables will appear
Answer is deducted because your answer is not: Time complexity O (N*log (N)) requirements

Can write like this

Var_dump (Solution ([1,3,5,3,7])), Var_dump (solution ([1,3,5,3,4])), function solution ($A) {  $arr = array ();  $len = count ($A);  $check = 0;       for ($i =0; $i < $len-1; $i + +) {    if ($A [$i +1] < $A [$i]) {      $temp = $A [$i +1];      $A [$i +1] = $A [$i];      $A [$i] = $temp;      if ($i > 0 && $A [$i-1] <= $A [$i]) $check + +;    }  }       return $check = = 1;}
BOOL (TRUE) bool (false)

Moderator of the first question of the solution, I have verified, indeed correct, feel with this ingenious function to remove a cycle.

I checked the introduction of Array_walk, still can not understand the moderator's subtle ideas. Can the moderator make a few remarks?

Also, the second topic, the revised code is as follows, for moderators and other great God test

$arr = Array (), $len = count ($A); $check = false; for ($i =0; $i < $len-1; $i + +) {for ($j = $i +1; $j < $len; $j + +) {$arr = $A; $temp = $arr [$j]; $arr [$j] = $arr [$i]; $arr [$i] = $ Temp $no _decrease = true;for ($k =1; $k < $len; $k + +) {if ($arr [$k]< $arr [$k-1]) {$no _decrease = false;}}    if ($no _decrease = = True) {$check = true;}}} return $check;


Look at the first question again.
The same results are not errors, but the algorithm does not conform to: the time complexity of O (N) requirements
You use a double loop, so the time complexity is O (n*n)
You can use closures to remove a heavy loop.

Var_dump (Solution ([1,0,-1,1,1,-1,-1], 2)), function solution ($A, $S) {  $len = count ($A);  $slice =-1;           for ($begin =0; $begin < $len; $begin + +) {    $total = 0;    Array_walk ($A, function ($v, $end, $S) use ($begin, & $slice, & $total) {      if ($end < $begin) return;      $total + = $v;      if ($total = = $S) {        $temp = $end-$begin + 1;        if ($temp > $slice) $slice = $temp;      }}    , $S);  }  return $slice;}

For the second question, I'm just doing it according to the example of the topic, and I did not consider the position of the interchange not adjacent to the situation
So I wonder why O (N*log (N))? O (N)) No, it's okay.
Rewrite it, please.

Var_dump (Solution ([1,3,5,3,7])) Var_dump (solution ([1,3,5,3,4])); Var_dump (solution ([1,6,3,4,3,7])); function solution ($A) {  $arr = array ();  $len = count ($A);  $check = 0;        for ($i =0; $i < $len-1; $i + +) {    if ($A [$i +1] < $A [$i]) {      $flag = 0;      for ($j = $i +1; $j < $len-1; $j + +) {        if ($A [$i] < $A [$j +1]) {          $flag = 1;          break;        }      }      $temp = $A [$j];      $A [$j] = $A [$i];      $A [$i] = $temp;      if ($i > 0 && $A [$i-1] <= $A [$i]) $check + +;      if (! $flag) $i--;    }  }  return $check = = 1;}
BOOL (TRUE) bool (FALSE) bool (true)

Simple judgment of time complexity
for () {
Code
}
==> O (N)

for () {
Code
for () {
Code
}
}
==> O (N*log (N))

for () {
for () {
Code
}
}
==> O (n*n)

Test your code carefully. There is no way to understand the moderator's ideas for a short time, but I have tested several examples, most of them correct, but still have problems.
For example, Var_dump (solution ([1,6,5,3,3,4,7]));
Visual inspection should not be successful at one time, but the return of the program is correct.

Because temporarily did not understand the moderator of the idea of the great God, so it is not good to comment, but I have been worried about non-decreasing non-descending, including the equal sign = the situation, such as the following
if ($A [$i] < $A [$j +1]) {
$flag = 1;
Break
}
where $A [$i] < $A [$j +1] need an equal sign?

Should I provide a test example that should return false?

For the second question, I'm just doing it according to the example of the topic, and I did not consider the position of the interchange not adjacent to the situation
So I wonder why O (N*log (N))? O (N)) No, it's okay.
Rewrite it, please.

Var_dump (Solution ([1,3,5,3,7])) Var_dump (solution ([1,3,5,3,4])); Var_dump (solution ([1,6,3,4,3,7])); function solution ($A) {  $arr = array ();  $len = count ($A);  $check = 0;        for ($i =0; $i < $len-1; $i + +) {    if ($A [$i +1] < $A [$i]) {      $flag = 0;      for ($j = $i +1; $j < $len-1; $j + +) {        if ($A [$i] < $A [$j +1]) {          $flag = 1;          break;        }      }      $temp = $A [$j];      $A [$j] = $A [$i];      $A [$i] = $temp;      if ($i > 0 && $A [$i-1] <= $A [$i]) $check + +;      if (! $flag) $i--;    }  }  return $check = = 1;}
BOOL (TRUE) bool (FALSE) bool (true)

if ($i > 0 && $A [$i-1] <= $A [$i]) $check + +; Exchange success, record
else return false; Exchange failed, returned. I missed it.

if ($A [$i] < $A [$j +1]) {
$flag = 1;
Break
}
To find the first position greater than $A [$i]
It doesn't matter if you want an equal

Modified as follows

Var_dump (Solution ([1,3,5,3,7])); Var_dump (solution ([1,3,5,3,4])); Var_dump (solution ([1,6,3,4,3,7])); Var_dump ( Solution ([1,6,5,3,3,4,7])); function solution ($A) {  $arr = array ();  $len = count ($A);  $check = 0;         for ($i =0; $i < $len-1; $i + +) {    if ($A [$i +1] < $A [$i]) {//if descending      $flag = 0;      for ($j = $i +1; $j < $len-1; $j + +) {//backwards to find the ascending position        if ($A [$i] < $A [$j +1]) {          $flag = 1;          break;        }      }      $temp = $A [$j]; Exchange      $A [$j] = $A [$i];      $A [$i] = $temp;      if ($i > 0 && $A [$i-1] <= $A [$i]) $check + +; The interchange succeeds      else return false;//Exchange Failed      if (! $flag) $i--;//$flag = 0 indicates that the previous lookup is a natural end and is debatable    }  return $c Heck = = 1;}

There is no doubt that xuzuning moderator is my idea of a goal, the program algorithm is very sharp, once again feel ah.
Don't say anything, it must be 100 points.

By the way, I looked up some information, in the reference to codility topic is generally hidden to the topic, because of the issue of copyright. Therefore, xuzuning Moderator, is not the title of the specific text hidden? or any other way to deal with it? It's just a suggestion.


Modified as follows

Var_dump (Solution ([1,3,5,3,7])); Var_dump (solution ([1,3,5,3,4])); Var_dump (solution ([1,6,3,4,3,7])); Var_dump ( Solution ([1,6,5,3,3,4,7])); function solution ($A) {  $arr = array ();  $len = count ($A);  $check = 0;         for ($i =0; $i < $len-1; $i + +) {    if ($A [$i +1] < $A [$i]) {//if descending      $flag = 0;      for ($j = $i +1; $j < $len-1; $j + +) {//backwards to find the ascending position        if ($A [$i] < $A [$j +1]) {          $flag = 1;          break;        }      }      $temp = $A [$j]; Exchange      $A [$j] = $A [$i];      $A [$i] = $temp;      if ($i > 0 && $A [$i-1] <= $A [$i]) $check + +; The interchange succeeds      else return false;//Exchange Failed      if (! $flag) $i--;//$flag = 0 indicates that the previous lookup is a natural end and is debatable    }  return $c Heck = = 1;}

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.