其他分享
首页 > 其他分享> > [简单]724. 寻找数组的中心下标

[简单]724. 寻找数组的中心下标

作者:互联网

https://leetcode-cn.com/problems/find-pivot-index/submissions/

 

没有灵魂的低端程序狗:

class Solution {
    public int pivotIndex(int[] nums) {
        if(nums.length == 1) {
            return 0;
        }
        int ret = -1;

        for (int i = 0; i < nums.length; i++) {
            if(i == 0) {
                int sum = 0;
                for (int j = 1; j < nums.length; j++) {
                    sum += nums[j];
                }
                if(sum == 0) {
                    return 0;
                }
            }
            else {
                int sumLeft  = 0;
                int sumRight = 0;
                // 左
                for (int m = 0; m < i; m++) {
                    sumLeft += nums[m];
                }
                // 右
                for (int n = i + 1; n < nums.length; n++) {
                    sumRight += nums[n];
                }
                if(sumLeft == sumRight) {
                    ret = i;
                    break;
                }
            }
        }
        return ret;
    }
}
View Code

 

标签:sumLeft,下标,nums,int,length,sumRight,++,724,数组
来源: https://www.cnblogs.com/chenxiaomai/p/16098222.html