Summary of common array questions in Java interviews (2)
Nov 09, 2020 pm 03:27 PM1. Fibonacci Sequence
[Topic]
Everyone knows the Fibonacci Sequence. Now we are asked to enter an integer n. Please output the nth term of the Fibonacci sequence (starting from 0, the 0th term is 0).
(Video tutorial recommendation: java course)
[Code]
package swear2offer.array; public class FeiBoNaQi { /** * 大家都知道斐波那契數(shù)列,現(xiàn)在要求輸入一個整數(shù) n, * 請你輸出斐波那契數(shù)列的第 n 項(從 0 開始,第 0 項為 0)。 * 0,1,1,2,3,5 * n<=39 * */ public int Fibonacci(int n) { if (n == 0) return 0; if (n == 1 || n== 2) return 1; return Fibonacci(n-1) + Fibonacci(n-2); } /** * 非遞歸方式,遞歸的數(shù)據(jù)結(jié)構(gòu)使用的棧,那就是使用棧的方式 * */ public int NoRecursive(int n) { if (n>2) { int[] a = new int[n+1]; a[0] = 0; a[1] = 1; a[2] = 1; for (int i=3; i<=n; i++) { a[i] = a[i-1] + a[i-2]; } return a[n]; } else { if (n == 0) return 0; else return 1; } } public static void main(String[] args) { System.out.println(new FeiBoNaQi().Fibonacci(39)); System.out.println(new FeiBoNaQi().Fibonacci(39)); } }
2. Rectangular coverage
[Title]
We can use the small rectangle of 21 to cover the larger rectangle horizontally or vertically. How many ways are there to cover a large 2*n rectangle with n small rectangles of size 21 without overlapping?
For example, when n=3, there are 3 covering methods for a 2*3 rectangular block:
Code:
package swear2offer.array; public class Rectangle { /** * f[0] = 0; * f[1] = 1; * f[2] = 2; * f[3] = 3; * f[4] = 5; * f[5] = 8; * f[n] = f[n-1] + f[n-2] * */ public int RectCover(int target) { if (target < 4) return target; int[] f = new int[target + 1]; int i; for (i=0; i<4; i++) f[i] = i; for (i=4; i<=target; i++) { f[i] = f[i-1] + f[i-2]; } return f[target]; } public static void main(String[] args) { System.out.println(new Rectangle().RectCover(5)); } }
[Thinking 】
The most straightforward way to solve the problem is to find the rules. From the summarized rules, we can see that this is the way to realize the Fibonacci sequence; the other is to answer the question according to the meaning of the question and find the method of n. , it is easy to think of solving this type of problem from n-1, and the first block is horizontal (f[n-2]) or vertical (f[n-1]), corresponding to different situations
(Recommendations for more related interview questions: java interview questions and answers)
3. The number of 1’s in binary
[Topic]
Input an integer and output the number of 1's in the binary representation of the number. Negative numbers are expressed in two's complement.
[Code]
package swear2offer.array; public class Binary { /** * 輸入一個整數(shù),輸出該數(shù)二進制表示中 1 的個數(shù)。其中負數(shù)用補碼表示。 * */ public int NumberOf1(int n) { int count; count = 0; while(n != 0) { n = n & (n-1);// 與操作就是二進制的操作,適用原碼和補碼 count ++; } return count; } }
[Thinking]
The one's complement of a negative number: The sign bit remains unchanged, and the remaining bits are inverted bit by bit. The complement of a negative number: in its one's complement On the basis of 1
If an integer is not 0, then at least one bit of this integer is 1. If we subtract 1 from this integer, then the original 1 on the rightmost side of the integer will become 0, and all the 0s after the original 1 will become 1 (if there are 0s after the rightmost 1). All remaining bits will be unaffected.
For example: a binary number 1100, the third digit from the right is the rightmost 1. After subtracting 1, the third digit becomes 0, the two following 0s become 1, and the previous 1 remains unchanged, so the result is 1011. We find that the result of subtracting 1 is to change the rightmost one All bits starting with 1 are inverted. At this time, if we do the AND operation between the original integer and the result after subtracting 1, all bits starting from the rightmost 1 of the original integer will become 0. For example, 1100&1011=1000. In other words, if you subtract 1 from an integer and then perform an AND operation with the original integer, the 1 on the rightmost side of the integer will be turned into 0. Then there are as many 1's as there are in the binary system of an integer. times such an operation.
4. Integer power of a value
[Title]
Given a floating-point number base of double type and an integer exponent of type int. Find base raised to the exponent power.
Ensure that base and exponent are not 0 at the same time
[Code]
package swear2offer.array; public class Power { public double Power(double base, int exponent) { if (base == 0) return 0; if (exponent == 0) return 1; int count; boolean flag; double temp; count = 1; temp = base; flag = true;// 標記正負 if (exponent < 0){ exponent = -exponent; flag = false; } while (count < exponent) { base *= temp; count ++; } if (flag) { return base; } else { return 1/base; } } public static void main(String[] args) { System.out.println(new Power().Power(2,-3)); } }
[Thinking]
This question is not difficult, and the algorithm is not very complicated, but the edge It is easy to miss corners and corners.
The first point is the positive and negative of exponent. It is easy to miss the negative number
Secondly, the cases of base==0 and exponent==0 are What’s different
Finally, when base is multiplied cumulatively, it cannot be used by itself, because base is constantly getting bigger.
5. Adjust the order of the array so that odd numbers are in front of even numbers
[Topic]
Input an array of integers and implement a function to adjust the order of numbers in the array so that all The odd numbers are located in the first half of the array, and all the even numbers are located in the second half of the array, ensuring that the relative positions between odd numbers and odd numbers, and even numbers and even numbers remain unchanged.
[Code]
package swear2offer.array; import java.util.Arrays; public class OddEven { /** * 輸入一個整數(shù)數(shù)組,實現(xiàn)一個函數(shù)來調(diào)整該數(shù)組中數(shù)字的順序, * 使得所有的奇數(shù)位于數(shù)組的前半部分,所有的偶數(shù)位于數(shù)組的后半部分, * 并保證奇數(shù)和奇數(shù),偶數(shù)和偶數(shù)之間的相對位置不變。 * * 時空復雜度較高的算法: * 新建一個數(shù)組b,用來保存奇數(shù),在重新變量一次,保存偶數(shù) * 時空復雜度0(n) * */ public void reOrderArray1(int [] array) { int n,i,j; n = array.length; int[] b = new int[n]; j = 0;// 用來保存數(shù)組B的下標 for (i=0; i<n; i++) { if (array[i]%2 != 0) { b[j] = array[i]; j ++; } } for (i=0; i<n; i++) { if (array[i]%2 == 0){ b[j] = array[i]; j++; } } for (i=0; i<n; i++) { array[i] = b[i]; } } /** * 采用的冒泡交換以及快速排序的思想: * 設(shè)定兩個游標,游標分別用來標記奇數(shù)和偶數(shù)的下標,然后交換二者 * 注意交換二者是無法保證順序的,交換的ij之間還有進行平移。 * */ public void reOrderArray(int [] array) { int n,i,j,temp,p; n = array.length; i = 0; j = 0; while (i<n && j<n) { // i標記偶數(shù)下標 while (i<n) { if (array[i]%2 ==0){ break; } else { i++; } } j = i; // j標記奇數(shù)下標 while (j<n) { if (array[j]%2 !=0){ break; } else { j++; } } if (i<n && j<n) { // 此時ij已經(jīng)在遇到的第一個偶數(shù)和奇數(shù)停下,把ij之間的內(nèi)容平移 temp = array[j]; for (p=j; p>i; p--) { array[p] = array[p-1]; } array[i] = temp; // 此時把i,j標記到 未交換前的偶數(shù)位置的下一個 i ++; j = i; } } } public static void main(String[] args) { int[] a = {1,4,6,3,2,5,8}; int[] b = {2,4,6,1,3,5,7}; new OddEven().reOrderArray(b); System.out.println(Arrays.toString(b)); } }
[Thinking]
Obviously, the way to create a new array is a tricky way. The question requires that operations be performed on this array. , the second method is to operate on this array, and this dual-cursor progressive method is very close to the idea of ??quick sort.
Related recommendations:Getting started with java
The above is the detailed content of Summary of common array questions in Java interviews (2). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa
