P6-寻找数组的中心下标
//寻找数组的中心下标
/*
* 给定一个整数数组nums,返回数组中心下标
* 中心:其左侧所有元素相加的和等于右侧所有元素相加的和
* 如果不存在,返回-1,如果有多个,返回最左边的一个
* */
public class P6 {
public static void main(String[] args) {
System.out.println(pivotIndex(new int[]{1,7,3,6,5,6}));
}
//双指针原理。右移
public static int pivotIndex(int[] nums) {
int sum = Arrays.stream(nums).sum();
int total = 0;
for(int i=0; i< nums.length; i++){
total += nums[i];
if(total == sum){
return i;
}
sum -= nums[i];
}
return -1;
}
/*
* 另一种思维
* 左边的sum和右边的sum
* 如果 lsum==rsum的话,证明 2*lsum+current == sum
* current右移
* 和上方的区别就是,这里是通过2*lsum+current == sum来得到lsum==rsum
* */
/*
* 二分法的话不太合适,因为没有说明是正整数,有可能是负数,从中间开始找不能保证是找到最左的
* 需要把指针从0开始右移来查找才能保证最左
* */
}
本文标题:P6-寻找数组的中心下标
本文链接:https://www.haomeiwen.com/subject/lffhdltx.html
网友评论