share O(N) solution!


  • 0
    T
    class Solution {
        public int pivotIndex(int[] nums) {
            if(nums==null || nums.length<3){
                return -1;
            }
            int sum = 0;
            for(int ele:nums){
                sum+=ele;
            }
            
            int left_sum = 0;
            for(int i=0;i<nums.length;i++){
                if(left_sum == sum-left_sum-nums[i]){
                    return i;
                }
                left_sum+=nums[i];
            }
            
            return -1;
        }
    }
    

Log in to reply
 

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