by a programming classic problem, exchange two variables of the value start, understand the program's space-time complexity (the following are the use of PHP code to demonstrate the solution of the problem)
one way to solve the problem:
1. Method text Description: Using an intermediate variable temp, to achieve the interchange of two variable values
2. Implementation of the specific code:
<?php//Declare two variable $ A, $b $a = $_get[' a ']; $b = $_get[' B ']; Before printing is not interchangeable, $a and $bvar_dump ("not replaced before: a={$a} and b={$b}");//Use intermediate variable $temp to achieve $ A and $b interchange $temp = $a; $a = $b; $b = $temp; Var_dump (" After replacing with the TEMP intermediate variable: a={$a} and b={$b} ");? >
3. Time and Space complexity
Time complexity is the number of program operations, 3 assignment operations
The space complexity is the memory size, except for the original $ A and $b two variables, the $TEMP intermediate variable is added, so the spatial complexity is 3 (3 strings in particular)
To reduce memory usage, avoid using intermediate variables, using XOR operators to implement
Two ways to solve the problem:
1. Method text Description: Using XOR operator
2. Implementation of the specific code:
<?php//Declare two variable $ A, $b $a = $_get[' a ']; $b = $_get[' B ']; Before printing is not interchangeable, $a and $bvar_dump ("not replaced before: a={$a} and b={$b}");//Use XOR operation to achieve $ A and $b interchange $ A = $a ^ $b; $b = $a ^ $b; $a = $a ^ $b; Var_dump ("Use XOR After substitution: a={$a} and b={$b} ");?>
3. Space-time complexity at this time
time, 3 assignment operation, 3 XOR operation, 6 times
space, using only the original 2 variables, $a and $b, with a spatial complexity of 2
Note: In PHP, the length of the preceding string is greater than or equal to the following string, because, for example,' abc ' ^ ' Defgh ', PHP will only execute ' abc ' ^ ' Def '. GH will be omitted .
This article is from the "PHP Related Technology blog" blog, please be sure to keep this source http://junstar.blog.51cto.com/4551565/1676808
Understanding the space-time complexity of a program by [exchanging two variable value problems]