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

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

Summary of common array questions in Java interviews (5)

Nov 16, 2020 pm 03:41 PM
java array interview

Summary of common array questions in Java interviews (5)

1. Number of times a number appears in a sorted array

[Title]

Count the number of times a number appears in a sorted array.

(Learning video recommendation: java video tutorial)

[Code]

public int GetNumberOfK(int [] array , int k) {

        if (array.length==0 || array==null) return 0;

        int i,n,count;
        n = array.length;

        count = 0;
        for (i=0; i<n; i++) {
            if (array[i] == k) count++;
        }

        return count;
    }

    public int high(int[] a, int k) {
        int start,end,mid;

        start = 0;
        end = a.length-1;

        while (start <= end) {
            mid = (start + end) >> 1;
            if (a[mid] <= k) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }

        return end;
    }

    public int low(int[] a, int k) {
        int start,end,mid;

        start = 0;
        end = a.length-1;

        while (start <= end) {
            mid = (start + end) >> 1;
            if (a[mid] >= k) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }

        return start;
    }

[Thinking]

Since the array is a Sorted array, so binary search can be used to locate the first and last occurrence of k. The time complexity is O(logN)O(logN)

Prerequisite for binary search: ordering (When it comes to order, you must immediately think of two points!)

2. Find 1 2 3 … n

[Title]

Find 1 2 3 … n, request Keywords such as multiplication and division, for, while, if, else, switch, case and conditional judgment statements (A?B:C) cannot be used.

[Code]

	public int Sum_Solution(int n) {
        int sum = n;
        boolean flag = (sum > 0) && (sum += Sum_Solution(n-1))>0;
        return sum;
    }

Thinking]

It is required that loops and judgments cannot be used, so recursion is used instead of loops, and short-circuit principle is used instead of judgments

The order of short-circuiting and execution is from left to right. After determining that the value of the first expression is false, there is no need to execute the second conditional statement. Because it is obvious that regardless of whether the second condition is true or false, the Boolean value of the entire expression must be false. Short-circuiting will skip the second conditional and not execute it. Based on these principles, the above results emerged. Flexible use of short-circuit and in programming is of great significance.

When n=0, sum=0, what follows && will not be executed, and sum=0 is returned directly

3. Cut the rope

[Title]

Given you a rope of length n, please cut the rope into m segments of integer length (m and n are both integers, n>1 and m>1), the length of each segment of rope is recorded as k [0],k[1],…,k[m]. What is the maximum possible product of k [0] xk [1] x...xk [m]? For example, when the length of the rope is 8, we cut it into three pieces with lengths 2, 3, and 3 respectively. The maximum product obtained at this time is 18.

【Code】

    /**
     * 給你一根長度為 n 的繩子,請把繩子剪成整數(shù)長的 m 段(m、n 都是整數(shù),n>1 并且 m>1),
     * 每段繩子的長度記為 k [0],k [1],...,k [m]。
     * 請問 k [0] xk [1] x...xk [m] 可能的最大乘積是多少?
     * 例如,當(dāng)繩子的長度是 8 時,
     * 我們把它剪成長度分別為 2、3、3 的三段,此時得到的最大乘積是 18。
     *
     * 使用動態(tài)規(guī)劃
     * 要點:邊界和狀態(tài)轉(zhuǎn)移公式
     * 使用順推法:從小推到大
     * dp[x] 代表x的最大值
     * dp[x] = max{d[x-1]*1,dp[x-2]*2,dp[x-3]*3,,,,},不需要全遍歷,取半即可
     * */
    public int cutRope(int target) {

        // 由于2,3是劃分的乘積小于自身,對狀態(tài)轉(zhuǎn)移會產(chǎn)生額外判斷
        if (target <= 3) return target-1;
        int[] dp = new int[target+1];
        int mid,i,j,temp;

        // 設(shè)定邊界
        dp[2] = 2;
        dp[3] = 3;

        for (i=4; i<=target; i++) {
            // 遍歷到中間即可
            mid = i >> 1;
            // 暫存最大值
            temp = 0;
            for (j=1; j<=mid; j++) {
                if (temp < j*dp[i-j]) {
                    temp = j*dp[i-j];
                }
            }
            dp[i] = temp;
        }

        return dp[target];

    }

Thinking

 *
 * 使用動態(tài)規(guī)劃
 * 要點:邊界和狀態(tài)轉(zhuǎn)移公式
 * 使用順推法:從小推到大
 * dp[x] 代表x的最大值
 * dp[x] = max{d[x-1]*1,dp[x-2]*2,dp[x-3]*3,,,,},不需要全遍歷,取半即可
 * 但是需要注意。2和3這兩個特殊情況,因為他們的分解乘積比自身要大,所以特殊處理

(More related interview questions to share: java interview questions and answers)

4. The maximum value of the sliding window

[Title]

Given an array and the size of the sliding window, find the maximum value of all values ??in the sliding window. For example, if the input array is {2,3,4,2,6,2,5,1} and the size of the sliding window is 3, then there are a total of 6 sliding windows, and their maximum values ??are {4,4,6, 6,6,5}; There are the following 6 sliding windows for the array {2,3,4,2,6,2,5,1}: {[2,3,4],2,6,2,5 ,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4 ,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5, 1]}.

【Code】

package swear2offer.array;

import java.util.ArrayList;

public class Windows {

    /**
     * 給定一個數(shù)組和滑動窗口的大小,找出所有滑動窗口里數(shù)值的最大值。
     * 例如,如果輸入數(shù)組 {2,3,4,2,6,2,5,1} 及滑動窗口的大小 3,
     * 那么一共存在 6 個滑動窗口,他們的最大值分別為 {4,4,6,6,6,5}
     *
     * 思路:
     * 先找出最開始size大小的最大值,以及這個最大值的下標(biāo)
     * 然后每次增加一個值,先判斷滑動窗口的第一位下標(biāo)是否超過保存最大值的下標(biāo)
     * 如果超過就要重新計算size區(qū)域的最大值,
     * 如果未超過就使用最大值與新增的元素比較,獲取較大的
     * */
    public ArrayList<Integer> maxInWindows(int [] num, int size) {
        ArrayList<Integer> list = new ArrayList<>();
        int i;
        int[] temp;
        temp = getMax(num,0,size);

        if (size<=0 || num==null || num.length==0) return list;

        // 當(dāng)窗口大于數(shù)組長度
        if (num.length <= size) return list;

        // 把第一個滑動窗口最大值加入數(shù)組
        list.add(temp[0]);

        // 從新的窗口開始計算,上一個窗口的最大值和下標(biāo)保存在temp中
        for (i=size; i<num.length; i++) {
            // 上一個最大值還在滑動窗口區(qū)域內(nèi)
            if (i-size < temp[1]) {
                if (temp[0] < num[i]) {
                    temp[0] = num[i];
                    temp[1] = i;
                }
            } else {
                temp = getMax(num,i-size+1,size);
            }
            list.add(temp[0]);
        }

        return list;
    }

    public int[] getMax (int[] num, int s, int size) {
        int [] res = new int[2];
        int e = s + size;
        // 當(dāng)窗口大于數(shù)組長度
        if (e>num.length) e = num.length;

        int temp = Integer.MIN_VALUE;
        int k = 0;
        for (int i=s; i<e; i++) {
            if (temp < num[i]) {
                temp = num[i];
                k = i;
            }
        }

        res[0] = temp;
        res[1] = k;

        return res;
    }

}

* Idea:

* First find the maximum value of the initial size and the subscript of this maximum value

* Then each time a value is added, first determine whether the first subscript of the sliding window exceeds the subscript that saves the maximum value

* If it exceeds, the maximum value of the size area must be recalculated,

* If it is not exceeded, use the maximum value to compare with the new element to obtain a larger value.

Additional supplement: For exceptions thrown, for example, in this question, the case of size>num.length is Throwing null, but I think it is the biggest throw, you should communicate with the interviewer at this time.

5. Repeated numbers in the array

[Title]

All numbers in an array of length n are in the range from 0 to n-1. Some numbers in the array are repeated, but I don't know how many numbers are repeated. I don't know how many times each number is repeated. Please find any repeated number in the array. For example, if the input is an array {2,3,1,0,2,5,3} of length 7, the corresponding output is the first repeated number 2.

【Code】

    /**
     * 在一個長度為 n 的數(shù)組里的所有數(shù)字都在 0 到 n-1 的范圍內(nèi)。
     * 數(shù)組中某些數(shù)字是重復(fù)的,但不知道有幾個數(shù)字是重復(fù)的。
     * 也不知道每個數(shù)字重復(fù)幾次。請找出數(shù)組中任意一個重復(fù)的數(shù)字。
     * 例如,如果輸入長度為 7 的數(shù)組 {2,3,1,0,2,5,3},
     * 那么對應(yīng)的輸出是第一個重復(fù)的數(shù)字 2。
     *
     * 思路:
     * 看到 長度n,內(nèi)容為0-n-1;瞬間就應(yīng)該想到,元素和下標(biāo)的轉(zhuǎn)換
     *
     * 下標(biāo)存的是元素的值,對應(yīng)的元素存儲出現(xiàn)的次數(shù),
     * 為了避免弄混次數(shù)和存儲元素,把次數(shù)取反,出現(xiàn)一次則-1,兩次則-2
     * 把計算過的位置和未計算的元素交換,當(dāng)重復(fù)的時候,可以用n代替
     * */
    public boolean duplicate(int numbers[],int length,int [] duplication) {

        if (length == 0 || numbers == null) {
            duplication[0] = -1;
            return false;
        }

        int i,res;
        i = 0;
        while (i < length) {
            // 獲取到數(shù)組元素
            res = numbers[i];
            // 判斷對應(yīng)位置的計數(shù)是否存在
            if (res < 0 || res == length) {
                i++;
                continue;
            }

            if (numbers[res] < 0) {
                numbers[res] --;
                numbers[i] = length;
                continue;
            }

            numbers[i] = numbers[res];
            numbers[res] = -1;
        }

        res = 0;
        for (i=0; i<length; i++) {
            if (numbers[i] < -1) {
                duplication[res] = i;
                return true;
            }
        }

        return false;
    }

* Idea:

* When you see the length n and the content is 0-n-1; you should immediately think of the conversion of elements and subscripts

* The subscript stores the value of the element, and the corresponding element stores the number of occurrences.

* In order to avoid confusion between the number and the stored element, the number is inverted. If it appears once, -1. Twice then -2

* Exchange the calculated position with the uncalculated element. When repeated, you can use n instead

Related recommendations: Java Getting Started

The above is the detailed content of Summary of common array questions in Java interviews (5). 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)

How to iterate over a Map in Java? How to iterate over a Map in Java? Jul 13, 2025 am 02:54 AM

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)-&gt

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

Comparable vs Comparator in Java Comparable vs Comparator in Java Jul 13, 2025 am 02:31 AM

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

How to handle character encoding issues in Java? How to handle character encoding issues in Java? Jul 13, 2025 am 02:46 AM

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

How to parse JSON in Java? How to parse JSON in Java? Jul 11, 2025 am 02:18 AM

There are three common ways to parse JSON in Java: use Jackson, Gson, or org.json. 1. Jackson is suitable for most projects, with good performance and comprehensive functions, and supports conversion and annotation mapping between objects and JSON strings; 2. Gson is more suitable for Android projects or lightweight needs, and is simple to use but slightly inferior in handling complex structures and high-performance scenarios; 3.org.json is suitable for simple tasks or small scripts, and is not recommended for large projects because of its lack of flexibility and type safety. The choice should be decided based on actual needs.

Java method references explained Java method references explained Jul 12, 2025 am 02:59 AM

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

Outlook shortcut for new email Outlook shortcut for new email Jul 11, 2025 am 03:25 AM

How to quickly create new emails in Outlook is as follows: 1. The desktop version uses the shortcut key Ctrl Shift M to directly pop up a new email window; 2. The web version can create new emails in one-click by creating a bookmark containing JavaScript (such as javascript:document.querySelector("divrole='button'").click()); 3. Use browser plug-ins (such as Vimium, CrxMouseGestures) to trigger the "New Mail" button; 4. Windows users can also select "New Mail" by right-clicking the Outlook icon of the taskbar

See all articles