[简单]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

 

posted @ 2022-04-04 01:23  v大喵  阅读(15)  评论(0编辑  收藏  举报