力扣 724.寻找数据的中心索引

题目描述

定义数组中心索引的:数组中心索引的左侧所有元素相加的和等于右侧所有元素相加的和。
给定一个整数类型的数组 nums,返回数组“中心索引”。如果数组不存在中心索引,那么返回 -1。如果数组有多个中心索引,那么返回最靠近左边的那一个。
注意:nums 的长度范围为 [0, 10000]。

示例

输入: nums = [1, 7, 3, 6, 5, 6]
输出: 3
解释: 索引3 (nums[3] = 6) 的左侧数之和(1 + 7 + 3 = 11),与右侧数之和(5 + 6 = 11)相等。同时, 3 也是第一个符合要求的中心索引。

输入: nums = [1, 2, 3]
输出: -1
解释: 数组中不存在满足此条件的中心索引。

解答
注意:如果中心索引 i 为0,则左侧和为0;如果 i 为length-1,则右侧和为0

解答1
遍历数组,分别计算当前num的左右两侧的和

class Solution {
    public int pivotIndex(int[] nums) {
        int temp;
        for (int i=0;i<nums.length;i++){
            int answer1=0,answer2=0;
            temp=i;
            //计算中心索引的左边的和
            for (int j=0;j<temp;j++){
                if (temp==0){
                    answer1=0;
                }
                else {
                    answer1+=nums[j];
                }
            }
            //计算中心索引右边的和
            for (int k=temp+1;k<nums.length;k++){
                answer2+=nums[k];
            }
            if (answer1==answer2){
                return temp;
            }
        }
        return -1;
    }
}

解答2:
只需要算出总数,挨个将每个元素都当作中心索引,进行计算:

public class Solution {
    public static void main(String[] args) {
        int[] nums={ 1, 7, 3, 6, 5, 6};
        System.out.println(pivotIndex(nums));
    }
    public static int pivotIndex(int[] nums) {
        int total=0;
        //算出总和
        for(int i=0;i<nums.length;i++){
            total+=nums[i];
        }
        for (int i=0;i<nums.length;i++){
            int temp=0,temp1=0;
            for (int j=0;j<i;j++){
                if (j==0){
                    temp=0;
                }
                temp+=nums[j];
            }
            temp1=total-temp-nums[i];
            if (temp==temp1){
                return i;
            }
        }
        return -1;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值