国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java JavaInterview questions Summary of common array questions in Java interviews (2)

Summary of common array questions in Java interviews (2)

Nov 09, 2020 pm 03:27 PM
java array interview

Summary of common array questions in Java interviews (2)

1. 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ù)據結構使用的棧,那就是使用棧的方式
     * */
    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:

Summary of common array questions in Java interviews (2)

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ù)來調整該數(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ù)的下標,然后交換二者
     * 注意交換二者是無法保證順序的,交換的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已經在遇到的第一個偶數(shù)和奇數(shù)停下,把ij之間的內容平移
                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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is a Singleton design pattern in Java? What is a Singleton design pattern in Java? Jul 09, 2025 am 01:32 AM

Singleton design pattern in Java ensures that a class has only one instance and provides a global access point through private constructors and static methods, which is suitable for controlling access to shared resources. Implementation methods include: 1. Lazy loading, that is, the instance is created only when the first request is requested, which is suitable for situations where resource consumption is high and not necessarily required; 2. Thread-safe processing, ensuring that only one instance is created in a multi-threaded environment through synchronization methods or double check locking, and reducing performance impact; 3. Hungry loading, which directly initializes the instance during class loading, is suitable for lightweight objects or scenarios that can be initialized in advance; 4. Enumeration implementation, using Java enumeration to naturally support serialization, thread safety and prevent reflective attacks, is a recommended concise and reliable method. Different implementation methods can be selected according to specific needs

What is a ThreadLocal in Java? What is a ThreadLocal in Java? Jul 09, 2025 am 02:25 AM

ThreadLocal is used in Java to create thread-private variables, each thread has an independent copy to avoid concurrency problems. It stores values ??through ThreadLocalMap inside the thread. Pay attention to timely cleaning when using it to prevent memory leakage. Common uses include user session management, database connections, transaction context, and log tracking. Best practices include: 1. Call remove() to clean up after use; 2. Avoid overuse; 3. InheritableThreadLocal is required for child thread inheritance; 4. Do not store large objects. The initial value can be set through initialValue() or withInitial(), and the initialization is delayed until the first get() call.

Java Optional example Java Optional example Jul 12, 2025 am 02:55 AM

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

How to fix java.io.NotSerializableException? How to fix java.io.NotSerializableException? Jul 12, 2025 am 03:07 AM

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

How to handle serialization and deserialization in Java? How to handle serialization and deserialization in Java? Jul 09, 2025 am 01:49 AM

Serialization is the process of converting an object into a storageable or transferable format, while deserialization is the process of restoring it to an object. Implementing the Serializable interface in Java can use ObjectOutputStream and ObjectInputStream to operate. 1. The class must implement the Serializable interface; 2. All fields must be serializable or marked as transient; 3. It is recommended to manually define serialVersionUID to avoid version problems; 4. Use transient to exclude sensitive fields; 5. Rewrite readObject/writeObject custom logic; 6. Pay attention to security, performance and compatibility

Explain the concept of autoboxing and unboxing in Java. Explain the concept of autoboxing and unboxing in Java. Jul 09, 2025 am 01:52 AM

AutoboxingandunboxinginJavaenableautomaticconversionbetweenprimitivesandtheirwrapperclasses.Autoboxingconvertsprimitivestowrapperobjects,suchaswhenaddinganinttoanIntegerlist,whileunboxingextractstheprimitivefromawrapper,likeassigninganIntegertoanint.

Python web scraping dynamic content Python web scraping dynamic content Jul 10, 2025 pm 12:18 PM

Dynamic web crawling can be achieved through an analysis interface or a simulated browser. 1. Use browser developer tools to view XHR/Fetch requests in the Network, find the interface that returns JSON data, and use requests to get it; 2. If the page is rendered by the front-end framework and has no independent interface, you can start the browser with Selenium and wait for the elements to be loaded and extracted; 3. In the face of the anti-crawling mechanism, headers should be added, frequency control, proxy IP should be used, and verification codes or JS rendering detection should be carried out according to the situation. Mastering these methods can effectively deal with most dynamic web crawling scenarios.

Python append to JSON file Python append to JSON file Jul 11, 2025 am 01:01 AM

To correctly add data to the JSON file, you must first read the original content, merge the new data, and then write it back as a whole. Common operation steps are as follows: 1. Read the contents of the JSON file to memory; 2. Append new data to the existing data structure (such as lists or dictionaries); 3. Rewrite the updated data to the file to overwrite the original content. For cases where the file does not exist or is empty, the exception should be caught and the empty list should be initialized before processing. If the JSON structure is a dictionary, you need to locate the specific key before adding it to ensure the correct format and avoid errors.

See all articles