2024华为OD机试真题【计算数组中心位置】【Java】

题目描述

给你一个整数数组nums,请计算数组的中心位置。数组的中心位置是数组的一个下标, 其左侧所有元素相乘的积等于右侧所有元素相乘的积。数组第一个元素的左侧积为1,最后一个元素的右侧积为1。 如果数组有多个中心位置,应该返回最靠近左边的那一个,如果数组不存在中心位置,返回-1。

输入

2 5 3 6 5 6

输出

3

题意解读

左侧积:该元素左侧所有元素的乘积;
右侧积:该元素右侧所有元素的乘积;

例如元素3,他的左侧积是 2*5 = 10. 他的右侧积是6*5*6 = 180
在这里插入图片描述

数组的中心位置指的是:该元素的 左侧积 等于 右侧积

解题思路

遍历整个数组,在遍历的过程中,计算当前元素左侧所有元素的乘积leftProduct )和右侧所有元素乘积rightProduct ),当leftProduct == rightProduct,表示找到了中心位置。

那么,如何初始化左侧积leftProduct 和右侧积 rightProduct 呢?leftProduct 初始值为 1,rightProduct初始值是所有元素相乘。

初始化完成后,开始遍历数组,从左到右的顺序遍历 。对于当前位置 i,首先更新左侧积(如果 i 不是第一个元素,那么左侧积为 leftProduct * nums[i-1]),然后更新右侧积(rightProduct / nums[i])。

扫描二维码关注公众号,回复: 17364356 查看本文章

如果左侧积和右侧积相等,则表示i就是中心点。

视频讲解

2023华为机试真题【计算数组中心位置】

示例代码(Java版本)

import java.util.Scanner;

public class Main {
    
    

    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        String[] inputs = scanner.nextLine().split(" ");
        int[] numbers = new int[inputs.length];
        
        for (int i = 0; i < inputs.length; i++) {
    
    
            numbers[i] = Integer.parseInt(inputs[i]);
        }

        int index = findCenterIndex(numbers);
        System.out.println(index);
    }

    public static int findCenterIndex(int[] nums) {
    
    
        if (nums.length == 1) {
    
    
            return 0;
        }

        int n = nums.length;
        int[] leftProduct = new int[n];
        int[] rightProduct = new int[n];

        leftProduct[0] = 1;
        rightProduct[n - 1] = 1;

        for (int i = 1; i < n; i++) {
    
    
            leftProduct[i] = leftProduct[i - 1] * nums[i - 1];
        }

        for (int i = n - 2; i >= 0; i--) {
    
    
            rightProduct[i] = rightProduct[i + 1] * nums[i + 1];
        }

        for (int i = 0; i < n; i++) {
    
    
            if (leftProduct[i] == rightProduct[i]) {
    
    
                return i;
            }
        }

        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/wtswts1232/article/details/135190589