zoukankan      html  css  js  c++  java
  • [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 all the numbers to the left of the index is equal to the sum of all 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: 3
    Explanation:
    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: -1
    Explanation:
    There is no index that satisfies the conditions in the problem statement.

    Constraints:

    • The length of nums will be in the range [0, 10000].
    • Each element nums[i] will be an integer in the range [-1000, 1000].

    寻找数组的中心索引。

    题意是给一个数组,找到一个中心索引。这个中心索引 i 的定义是使得数组在 i 左边的子数组的和 = 数组在 i 右边的子数组的和,其中左右两边的计算不包括nums[i]。

    思路是前缀和。我们先计算整个数组的前缀和sum。再次扫描数组,此时我们需要再找一个左起的前缀和 leftSum ,同时找一个index满足 leftSum = sum - nums[i] - leftSum。如果能找到就返回这个index,如果找不到就返回-1。

    时间O(n)

    空间O(1)

    Java实现

     1 class Solution {
     2     public int pivotIndex(int[] nums) {
     3         int sum = 0;
     4         for (int num : nums) {
     5             sum += num;
     6         }
     7 
     8         int leftSum = 0;
     9         for (int i = 0; i < nums.length; i++) {
    10             if (leftSum == sum - nums[i] - leftSum) {
    11                 return i;
    12             }
    13             leftSum += nums[i];
    14         }
    15         return -1;
    16     }
    17 }

    LeetCode 题目总结

  • 相关阅读:
    jenkins配置html报告
    JMeter并发测试(设置集合点)
    jmeter压力测试 设置一秒发送一次请求,一秒两次请求
    jmeter压力测试的简单实例+badboy脚本录制
    JMeter问题集
    英语自然拼读法基本规则和小窍门
    Jmeter工具做性能测试 常见的错误汇总
    如何使用JDK自带工具JConsole
    第七章 JMeter 逻辑控制器
    第六篇:JMeter 断言
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13900751.html
Copyright © 2011-2022 走看看