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;
    }
Copy after login

[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;
    }
Copy after login

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 的绳子,请把绳子剪成整数长的 m 段(m、n 都是整数,n>1 并且 m>1),
     * 每段绳子的长度记为 k [0],k [1],...,k [m]。
     * 请问 k [0] xk [1] x...xk [m] 可能的最大乘积是多少?
     * 例如,当绳子的长度是 8 时,
     * 我们把它剪成长度分别为 2、3、3 的三段,此时得到的最大乘积是 18。
     *
     * 使用动态规划
     * 要点:边界和状态转移公式
     * 使用顺推法:从小推到大
     * 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是划分的乘积小于自身,对状态转移会产生额外判断
        if (target <= 3) return target-1;
        int[] dp = new int[target+1];
        int mid,i,j,temp;

        // 设定边界
        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];

    }
Copy after login

Thinking

 *
 * 使用动态规划
 * 要点:边界和状态转移公式
 * 使用顺推法:从小推到大
 * dp[x] 代表x的最大值
 * dp[x] = max{d[x-1]*1,dp[x-2]*2,dp[x-3]*3,,,,},不需要全遍历,取半即可
 * 但是需要注意。2和3这两个特殊情况,因为他们的分解乘积比自身要大,所以特殊处理
Copy after login

(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 {

    /**
     * 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。
     * 例如,如果输入数组 {2,3,4,2,6,2,5,1} 及滑动窗口的大小 3,
     * 那么一共存在 6 个滑动窗口,他们的最大值分别为 {4,4,6,6,6,5}
     *
     * 思路:
     * 先找出最开始size大小的最大值,以及这个最大值的下标
     * 然后每次增加一个值,先判断滑动窗口的第一位下标是否超过保存最大值的下标
     * 如果超过就要重新计算size区域的最大值,
     * 如果未超过就使用最大值与新增的元素比较,获取较大的
     * */
    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;

        // 当窗口大于数组长度
        if (num.length <= size) return list;

        // 把第一个滑动窗口最大值加入数组
        list.add(temp[0]);

        // 从新的窗口开始计算,上一个窗口的最大值和下标保存在temp中
        for (i=size; i<num.length; 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;
        // 当窗口大于数组长度
        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;
    }

}
Copy after login

* 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 的数组里的所有数字都在 0 到 n-1 的范围内。
     * 数组中某些数字是重复的,但不知道有几个数字是重复的。
     * 也不知道每个数字重复几次。请找出数组中任意一个重复的数字。
     * 例如,如果输入长度为 7 的数组 {2,3,1,0,2,5,3},
     * 那么对应的输出是第一个重复的数字 2。
     *
     * 思路:
     * 看到 长度n,内容为0-n-1;瞬间就应该想到,元素和下标的转换
     *
     * 下标存的是元素的值,对应的元素存储出现的次数,
     * 为了避免弄混次数和存储元素,把次数取反,出现一次则-1,两次则-2
     * 把计算过的位置和未计算的元素交换,当重复的时候,可以用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) {
            // 获取到数组元素
            res = numbers[i];
            // 判断对应位置的计数是否存在
            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;
    }
Copy after login

* 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles