Today encounter a face questions: input n, if n <= 1, f (n) = 1, else f (n) = f (n-1) + f (n-2), the print f (n) from 1 the value of n.
public class Fibonacci { private int n; private StringBuilder sb; private String format; @Before public void init() { n = 10; sb = new StringBuilder(n); format = "f(%s) = "; }
Directly implemented recursively:
/** * 递归实现 */ @Test public void recursion() { for (int i = 1; i <= n; i++) { sb.delete(0, n); sb.append(String.format(format, i)); sb.append(recursion(i)); System.out.println(sb.toString()); } } private int recursion(int n) { if (n <= 1) { return 1; } else { return recursion(n - 1) + recursion(n - 2); } }
Test results are as follows:
The interviewer said with a circulation loop to achieve:
/ ** * for loop implemented * / @Test public void Fori () { IF (n-<=. 1 ) { System.out.println ( . 1 ); } int J =. 1, K =. 1 ; int SUM; for ( int 2 = I; I <= n-; I ++ ) { // F (n-) = F (n--. 1) + F (n-2-) // the j as f (n-1), k as f (n- 2) SUM = J + K; K = J; J = SUM; sb.delete ( 0 , n-); sb.append(String.format(format, i)); sb.append(sum); System.out.println(sb.toString()); } }
Test results are as follows:
He said the code can be more streamlined, efficient and modified again:
/ ** * loop for more efficient implementation * / @Test public void forEfficient () { IF (n-<=. 1 ) { System.out.println ( . 1 ); } int TEMP =. 1 ; int SUM =. 1 ; for ( int 2 = I; I <= n-; I ++ ) { // f (n-) = f (n--. 1) + f (2-n-) // this case as the sum f (n-1), temp as f ( 2-n-) sum = sum + TEMP; // the calculated sum is F (n-) // TEMP = F (n--. 1) = F (n-) - F (n-2-) temp = sum - temp; sb.delete(0, n); sb.append(String.format(format, i)); sb.append(sum); System.out.println(sb.toString()); } }
Test results are as follows:
Face behind a few questions related programming issues:
To a disordered array, find the first K a big number
For example 23, 5, 7, 2, of 2 large number is 7 ;
Quicksort partition functions, such as 10 number, find the first 5 large number, in descending order, after a fast row, is returned if the subscript 2 is the final position of this number, and this number the left than all it is large, all the numbers on the right than he was little, and then find the 3-9 numbers be Partition ......
If there is an ordered array of issues related to, it should be thought of binary search , according to an array subscript half!
A lot of the programming problem, simply feel at school recruit, recruit community need to think about in order to do it.