【发布时间】:2019-11-30 10:16:43
【问题描述】:
我需要返回元素的索引,其中左侧元素的总和等于右侧元素的总和。例如,对于数组 [-3, 8, 3, 1, 1, 3],返回值为索引 2,因为前 3 ([-3, 8]) 左侧元素的总和与右侧元素的总和 ([1, 1, 3])。
所以我开始使用线性搜索功能来查找预期的索引, 然后之后我尝试拆分所选索引的左右数组,但没有成功
我没有成功让它工作
//linear-search portion,x is the index selected to be split point
public static int findindex(int arr[], int x) {
//if array is null
if (arr == null) {
return -1;
}
//find array length
int len = arr.length;
int i = 0;
//traverse the array
while (i < len) {
//if the i-th element is is x then return the index
if (arr[i] == x) {
return i;
} else {
i = i + 1;
}
}
//splint array portion,returns index if not possible
int leftsum = 0;
//treverse array elements
for (int i = 0; i < x; i++) {
//adds current elements to left
leftsum += arr[i];
//find sum of remader the array elements to rightsum
int rightsum = 0;
for (int j = i + 1; j < x; J++)
rightsum += arr[j];
//split pint index
if (leftsum == rightsum)
return i + 1;
}
//if not possible return
return -1;
}
// driver code
public static void main(String[] args) {
int[] array1 = { -3, 8, 3, 1, 1, 3 };
System.out.println(findindex(array1));
}
【问题讨论】:
-
请edit您的问题并缩进代码以便我们阅读。
-
请阅读“如何创建minimal reproducible example”。然后使用edit 链接改进您的问题(不要通过 cmets 添加更多信息)。否则我们无法回答您的问题并为您提供帮助。 “但没有成功”不是有效的问题描述。是的:您希望其他人利用他们的空闲时间来帮助您解决问题,因此请花几分钟时间来正确格式化/删除您的所有输入。
-
什么是
int x作为findindex方法的参数? -
int x 是索引点,将数组分成两等份