O(n) Solution


  • 0
    F

    O(n) solution

    class Solution {
        public int pivotIndex(int[] nums) {
            if (nums == null || nums.length == 0) {
                return -1;
            }
            int leftSum = 0, rightSum = 0;
            for (int num : nums) {
                rightSum += num;
            }
            for (int i = 0; i < nums.length; i++) {
                rightSum -= nums[i];
                if (leftSum == rightSum) {
                    return i;
                }
                leftSum += nums[i];
            }
            
            return -1;
        }
    }
    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.