[Java/C++] Clean Code


  • 5

    Java

    class Solution {
        public int pivotIndex(int[] nums) {
            int total = 0, sum = 0
            for (int num : nums) total += num;
            for (int i = 0; i < nums.length; sum += nums[i++])
                if (sum * 2 == total - nums[i]) return i;
            return -1;  
        }
    }
    

    C++

    class Solution {
    public:
        int pivotIndex(vector<int>& nums) {
            int total = 0;
            for (int num : nums) total += num;
            int sum = 0;
            for (int i = 0; i < nums.size(); sum += nums[i++])
                if (sum * 2 == total - nums[i])
                    return i;
            
            return -1;
        }
    };
    

Log in to reply
 

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