简体   繁体   English

如何在 java 中不定义大小的情况下获取 N 个元素的输入数组

[英]How to take input array of N elements without defining size in java

Input: In the input, there will be an array of N element输入:在输入中,会有一个N元素的数组

Output: Output will be the number that is the sum of its left and right sub-arrays. Output:Output 将是其左右子数组之和的数字。

Example Input: 2 3 5 20 5 3 2示例输入:2 3 5 20 5 3 2

Output: 20 Output:20

Input: 5 10 20 122 30 12 9 36输入:5 10 20 122 30 12 9 36

Output: 122 Output:122

Anyone can explain this question how it will be solved as I am applying logic as the output will be the middle element of the array but is this true logic.任何人都可以解释这个问题将如何解决,因为我正在应用逻辑,因为 output 将是数组的中间元素,但这是真正的逻辑。 Also, for increasing the size of an array at runtime we can use ArrayList but how it will be declared can anyone suggest code.此外,为了在运行时增加数组的大小,我们可以使用 ArrayList 但是任何人都可以建议代码如何声明它。 Thank you.谢谢你。

You basically need to find the element which is equals to the sum of its right and left elements.您基本上需要找到等于其左右元素之和的元素。 Below program should achieve the same.下面的程序应该达到同样的效果。

public class Sample {
    public static void main(String[] args) {
        int arr[] = { 5, 10, 20, 122, 30, 12, 9, 36 };
        for (int i = 0; i < arr.length; i++) {
            int temp = arr[i];
            int sum = 0;
            if (i == 0) {
                // first element simple sum the right elements
                for (int j = i + 1; j < arr.length; j++) {
                    sum += arr[j];

                }

            } else {
                // sum the right elements
                for (int j = i + 1; j < arr.length; j++) {
                    sum += arr[j];

                }
                // sum the left elements
                for (int j = i - 1; j >= 0; j--) {
                    sum += arr[j];

                }
                // check if sum of left and right elements equals element.
                if (sum == arr[i]) {
                    System.out.println(arr[i]);
                    break;
                }
            }

        }

    }
}

i think you have to just calc the total sum and subtract every number from it in array and when after substraction of ith no from total sum gives again that ith number means this number is equal to sum of all other right and left subarray我认为你必须只计算总和并从中减去数组中的每个数字,当从总和中减去第 i 个数字后再次给出第 i 个数字意味着这个数字等于所有其他左右子数组的总和

l=list(map(int,input().split(' ')))
x=sum(l)
y=0

for i in range(len(l)):
    y=x-l[i]
    if(y==l[i]):
        print(l[i])
        break;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM