Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/find-pivot-index/
- /**
- * Prefix Sum
- *
- * leftSum = rightSum (Excluding the pivot point)
- *
- * rightSum = TotalSum - leftSum - nums[pivotPoint]
- *
- * Time Complexity: O(N)
- *
- * Space Complexity: O(1)
- *
- * N = Length of the input nums array.
- */
- class Solution {
- public int pivotIndex(int[] nums) {
- if (nums == null || nums.length == 0) {
- return -1;
- }
- int sum = 0;
- int leftSum = 0;
- for (int num : nums) {
- sum += num;
- }
- for (int i = 0; i < nums.length; i++) {
- if (leftSum == sum - leftSum - nums[i]) {
- return i;
- }
- leftSum += nums[i];
- }
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement