寻找数组的中心索引

This commit is contained in:
LingZhaoHui 2020-08-16 14:57:47 +08:00
parent bb8f35cfef
commit 28542a33ef
2 changed files with 40 additions and 1 deletions

2
.gitignore vendored
View File

@ -1,3 +1,3 @@
target
.idea
*.swp

39
src/list/PivotIndex.java Normal file
View File

@ -0,0 +1,39 @@
package list;
/**
* @file PivotIndex.java
* @apiNote https://leetcode-cn.com/leetbook/read/array-and-string/yf47s/
* @author zeekling
* @version 1.0
* @date 2020-08-16
*/
public class PivotIndex {
public int pivotIndex(int[] nums){
int sum = 0;
int len = nums.length;
for (int i=0; i< len;i++){
sum += nums[i];
}
int idx = -1;
int leftSum = 0;
for (int i=0;i<len;i++){
if ((leftSum * 2 + nums[i]) == sum){
return i;
}
leftSum += nums[i];
}
return -1;
}
public static void main(String[] args){
int[] arr = new int[]{1, 7, 3, 6, 5, 6};
PivotIndex pro = new PivotIndex();
int res = pro.pivotIndex(arr);
System.out.println(res);
}
}