leetcode 724 Find Pivot Index

题目详情

Given an array of integers nums, write a method that returns the "pivot" index of this array.
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.

题目的意思要找出输入数组的“枢纽”点。这个“枢纽”的定义就是,这个元素全部左边的元素的加和恰好等于它全部右边元素的加和,而且咱们返回这个枢纽点的位置。若是不存在这样的“枢纽”,则返回-1.若是有多个这样的枢纽,则返回最左侧的枢纽点。数组

Example 1:
Input:
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation:
nums[3]左边的元素和为11,恰好等于nums[3]右边的元素和。
Example 2:
Input:
nums = [1, 2, 3]
Output: -1
Explanation:
没有知足“枢纽”定义的元素。因此返回-1.this

想法

  • 有一种临界状况须要考虑,就是元素nums[0]做为枢纽点的状况,这种状况下,nums[0]的全部的右边的元素加和应该为0,则nums[0]为数组的枢纽点。
  • 考虑了这个特殊状况就没有什么特别的了。咱们先遍历一趟得到数组元素值的和sum。
  • 在第二趟遍历中,检查当前元素左边全部元素的加和,是否等于sum减去当前元素的值,若是知足,则当前点为枢纽点,返回当前元素的位置。

解法

public int pivotIndex(int[] nums) {
        int length = nums.length;
        if(length == 0 || length ==1)return -1;
        int sum = 0;
        
        for(int num : nums)sum += num;
        
        if(sum-nums[0] == 0)return 0;
        int left = 0;
        for(int i=1;i<length;i++){
            left += nums[i-1];
            if(sum - left - nums[i] == left){
                return i;
            }
        }
        
        return -1;
    }
相关文章
相关标签/搜索