Zhongan insurance written test java

baseShanghai

Multiple choice questions: java basics

Programming questions: 2

1. The product of an array other than itself (leetcode 238)

Given an integer array nums, return an array answer where answer[i] is equal to the product of all elements in nums except nums[i].

The topic data guarantees that the product of all prefix elements and suffixes of any element in the array nums is within the range of 32-bit integers.

Please don't use division and solve this problem in O(n) time complexity.

Example 1:

Input: nums = [1,2,3,4]
Output: [24,12,8,6]

Example 2:

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

Official solution:

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int length = nums.length;

        // L 和 R 分别表示左右两侧的乘积列表
        int[] L = new int[length];
        int[] R = new int[length];

        int[] answer = new int[length];

        // L[i] 为索引 i 左侧所有元素的乘积
        // 对于索引为 '0' 的元素,因为左侧没有元素,所以 L[0] = 1
        L[0] = 1;
        for (int i = 1; i < length; i++) {
            L[i] = nums[i - 1] * L[i - 1];
        }

        // R[i] 为索引 i 右侧所有元素的乘积
        // 对于索引为 'length-1' 的元素,因为右侧没有元素,所以 R[length-1] = 1
        R[length - 1] = 1;
        for (int i = length - 2; i >= 0; i--) {
            R[i] = nums[i + 1] * R[i + 1];
        }

        // 对于索引 i,除 nums[i] 之外其余各元素的乘积就是左侧所有元素的乘积乘以右侧所有元素的乘积
        for (int i = 0; i < length; i++) {
            answer[i] = L[i] * R[i];
        }

        return answer;
    }
}

Of course, the violent solution can also pass the test

2. The kth largest element (leetcode 215)

Given an integer array nums and an integer k, return the kth largest element in the array.

Example 1:

Input: [3,2,1,5,6,4], k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6], k = 4
Output: 4

Brute force solution:

class Solution {
    public int findKthLargest(int[] nums, int k) {
        Arrays.sort(nums);
        return nums[nums.length-k];
    }
}

Guess you like

Origin blog.csdn.net/m0_56170277/article/details/129899632