Cheng Zheng has solved two test questions on codility, and has a great test of intelligence and ability! (I was hit badly. let's see how it works)

Source: Internet
Author: User
Cheng Zheng has solved two test questions on codility, and has a great test of intelligence and ability! (I was hit badly. let's take a look.) if you don't talk about it, you have the opportunity to do two tests on codility and use php to solve it. I wrote two programs, and I thought it was okay. but as soon as I came out, I got 50 points for 200 points. Cheng Zheng pointed out the errors in my program and the solution of the experts.
Let's not talk about anything. First, let's start with the question:
1. You are given a non-empty zero-indexed array A consisting of N integers. Each element of 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. 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 are exactly two 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, 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 shoshould 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 shoshould return 5, as explained ABVE.

Assume that:

N and S are integers within the range [1 .. 100,000];
Each element of array A is 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. this operation takes two 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 sort Ming 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 is sorted in non-decreasing order.

Write a function:

Function solution ($ );

That, given a non-empty zero-indexed array A consisting of N integers, returns true if the array can be sorted into non-decreasing 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 shoshould return true, as explained ABVE.

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 shocould 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 array A is an integer 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 badly and scored 50 out of the last 200 points. How many points do you get?


Reply to discussion (solution)

Nima, take A closer look. my program has A major error in the second question. $ arr = $ A; should be placed behind the second.
Dizzy.

I do not know English .. 0 points

You can get 10 points for the day after posting.

Is there no big God to solve it? In particular, the second question is quite difficult.

First look at the second question
The original code calculation result is correct, and the #1 supplement is incorrect!
If $ arr = $ A; is placed behind the second for, A series of warnings about using undefined variables will appear.
The reason for the deduction is that your answer does not meet the requirements of O (N * log (N ).

You 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)

Let's look at the first question.
The calculation result is correct, but the algorithm does not meet the requirements of O (N ).
You use a dual loop, so the time complexity is O (N * N)
A closure can be used to remove a 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 choosing the moderator.
However, I have different opinions on the second question:
1. your idea is: check the adjacent two sizes. if the value on the right is smaller than the value on the left, change the value. if the value on the right is smaller than the value on the left, check ++.
In fact, I thought about this idea when I was doing the question, but I thought about this example:, 3, 7. if you change 6 and the second 3, the non-descending sequence can be satisfied, and the last value should be true. However, according to your algorithm, false is returned for this question.

The key point is that the exchange of numbers can be a clever one.

2. in the second question, $ arr = $ A; should be placed behind the second for, and I have verified it again, so there will be no errors such as undefined objects. The result is correct.
My idea is to assign $ A to $ arr every time, and use the exhaustive method to change any two different numbers once to determine whether the result after the change is A non-descending sequence. If yes, true is returned. If no, the false value of check is not changed. As long as you can do this once in the exhaustive method, the check value becomes true.

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

Moderator, what do you think?


First look at the second question
The original code calculation result is correct, and the #1 supplement is incorrect!
If $ arr = $ A; is placed behind the second for, A series of warnings about using undefined variables will appear.
The reason for the deduction is that your answer does not meet the requirements of O (N * log (N ).

You 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)

I have verified the solution to the first question of the moderator. it is true and I feel that this clever function is used to remove a loop.

I checked the introduction of array_walk, but I still cannot understand the exquisite ideas of the moderator. Can the moderator provide two comments?

Also, for the second question, the adjusted code is as follows for the moderator and other great gods to 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;


Let's look at the first question.
The calculation result is correct, but the algorithm does not meet the requirements of O (N ).
You use a dual loop, so the time complexity is O (N * N)
A closure can be used to remove a 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 just follow the example of the question and do not consider the situation where the exchange location is not adjacent.
So Why O (N * log (N? O (N) isn't it enough?
Rewrite

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 determination of time complexity
For (){
Code
}
==> O (N)

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

For (){
For (){
Code
}
}
==> O (N * N)

Carefully tested your code. I have not been able to understand the idea of the moderator for a short time, but I have tested several more examples. most of them are correct, but there are still problems.
For example, var_dump (solution ([, 7]);
The switch should fail once, but the program returns correct.

I have not understood the idea of the moderator yet, so it is not easy to comment, but I have been worried about non-decreasing non-downgrading, including equal sign =, for example, below
If ($ A [$ I] <$ A [$ j + 1]) {
$ Flag = 1;
Break;
}
Do you need an equal sign for $ A [$ I] <$ A [$ j + 1?

Should I return false for the test example I provided?

For the second question, I just follow the example of the question and do not consider the situation where the exchange location is not adjacent.
So Why O (N * log (N? O (N) isn't it enough?
Rewrite

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 successful, record
Else return false; // exchange failed, return. Previously missed

If ($ A [$ I] <$ A [$ j + 1]) {
$ Flag = 1;
Break;
}
Is to find the first location greater than $ A [$ I]
It doesn't matter if you want to equal the number.

After modification

Var_dump (solution ([, 7]); var_dump (solution ([, 4]); var_dump (solution, ]); var_dump (solution ([, 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 the descending order $ flag = 0; for ($ j = $ I + 1; $ j <$ len-1; $ j ++) {// locate the position in ascending order 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 ++; // switch successful else return false; // switch failed if (! $ Flag) $ I --; // $ flag = 0 indicates that the previous search ends naturally. to be discussed,} return $ check = 1 ;}

Without a doubt, the xuzuning moderator is a goal in my mind. The program algorithm is very sharp and I feel it again.
Don't say anything. it must be 100 points.

By the way, I have checked some materials. I usually refer to the topic of codility because it involves copyright issues. Therefore, does the xuzuning moderator hide the specific text of the question? Or other processing methods? It's just a suggestion.


After modification

Var_dump (solution ([, 7]); var_dump (solution ([, 4]); var_dump (solution, ]); var_dump (solution ([, 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 the descending order $ flag = 0; for ($ j = $ I + 1; $ j <$ len-1; $ j ++) {// locate the position in ascending order 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 ++; // switch successful else return false; // switch failed if (! $ Flag) $ I --; // $ flag = 0 indicates that the previous search ends naturally. to be discussed,} return $ check = 1 ;}

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.