[C] Simple C solution (O(n))


  • 0
    P

    Move the pivot pointer from left to right, and compare left-sum and right-sum in each iteration.
    Time complexity: O(n)

    int pivotIndex(int* nums, int numsSize) {
        int pivot = 0, i = 0;
        int lsum = 0, rsum = 0;
    
        for(i=pivot+1;i<numsSize;i++)
            rsum+=nums[i];
    
        while(pivot < numsSize) {
            if(rsum == lsum)
                return pivot;
            lsum += nums[pivot];
            rsum -= nums[++pivot];
        }
        return -1;
    }
    

Log in to reply
 

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