LEETCODE: 724. Find Pivot Index
来源:互联网 发布:lol免费皮肤软件 编辑:程序博客网 时间:2024/05/21 21:01
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.
Example 1:
Input: nums = [1, 7, 3, 6, 5, 6]Output: 3Explanation: The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.Also, 3 is the first index where this occurs.
Example 2:
Input: nums = [1, 2, 3]Output: -1Explanation: There is no index that satisfies the conditions in the problem statement.
Note:
The length of nums will be in the range [0, 10000].
Each element nums[i] will be an integer in the range [-1000, 1000].
难度:easy
看到这个题目,坐下来想5分钟。最简单的方法,就是遍历所有位置,然后分别计算左边所有元素的和,以及右边所有元素的和,如果它们相等,那么符合条件,返回。
for number in nums 计算左边元素之和 nums[0] + nums[1] + nums[left] 计算右边元素之和 nums[right] + nums[right+1] + nums[n-1] if 左边的和 == 右边的和 返回 元素的 index
但是每次都计算左/右边元素之和,效率不高。如果数组是从 0 一直遍历到 n-1 的,并且已知他们的和为 sum。那么:
由此可见,每一步的左边之和,可以是 上一步的左边之和 加上 当前的左边元素 的和。每一步的右边之和,可以是 上一步的右边之和 减去 当前元素 的结果。
代码如下:
class Solution {public: int pivotIndex(vector<int>& nums) { int n = nums.size(); int sum = 0; for(int ii = 0; ii < n; ii ++) { sum += nums[ii]; } int leftSum = 0; int rightSum = sum; for(int ii = 0; ii < n; ii ++) { leftSum += ii > 0 ? nums[ii - 1] : 0; rightSum -= nums[ii]; if(leftSum == rightSum) { return ii; } } return -1; }};
- LeetCode 724. Find Pivot Index
- LEETCODE: 724. Find Pivot Index
- LeetCode-724. Find Pivot Index
- 724. Find Pivot Index
- 724. Find Pivot Index
- LeetCode.724 Find Pivot Index
- leetcode 724 Find Pivot Index
- Find Pivot Index[Leetcode 724]
- Find Pivot Index(LeetCode 724)
- LWC 58:724. Find Pivot Index
- LeetCode724. Find Pivot Index
- [LeetCode]Find Pivot
- Find Pivot Index问题及解法
- leetcode index
- PIVOT
- pivot
- PIVOT
- pivot
- 热门又高薪的大数据技术,怎么上车,前景如何?
- 第5次作业
- C语言知识小结(二)
- java GUI实现记事本
- 购物车+自定义拦截器
- LEETCODE: 724. Find Pivot Index
- 5. 方法与数组
- xLua的学习笔记
- HTML——<input>、<select>
- transform属性
- 3
- MVP框架使用Retrofit+Rxjava请求网络数据
- 条件概率 -- P(A|B) P(B|A)
- Markdown编辑器的用法(转自官方(滑稽))——为了方便写博客