数组-寻找数组的中心索引

时间:2020-08-25 15:45:09   收藏:0   阅读:55

题目描述

技术图片

思路

技术图片

代码实现

package com.zxl.数组.查找索引;
public class Demo03 {
    public static void main(String[] args) {
        int[] arrays = new int[]{1, 7, 3, 6, 5};
        int center = getCenterIndex(arrays);
        System.out.println(center);
    }

    // 获取中心索引
    public static int getCenterIndex(int[] nums) {
        int sum = 0;
        for (int array : nums) {
            sum += array;
        }
        for (int i = 0; i <= nums.length - 1; i++) {
            int sumLeft = 0;
            int sumRight = 0;
            for (int j = i - 1;j >= 0; j--) {
                sumLeft += nums[j];
            }
            sumRight = sum - sumLeft - nums[i];
            if (sumLeft == sumRight) {
                return i;
            }
        }
        return -1;
    }
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!