zoukankan      html  css  js  c++  java
  • 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.

    找到一个位置i使得sum(nums[0:i]) == sum(nums[i + 1:]) 如果有多个,返回最左的i,否则返回-1

    这题其实比较简单,求一个左前缀和和右前缀和就可以了,比较恶心的就是边界[1,0,0,-1,1]这个答案是0以及[-1,-1,1,1,1] 答案是4。需要小心一些边界

    class Solution(object):
        def pivotIndex(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            n = len(nums)
            if n < 3:
                return -1
            left = [0] * (n + 2)
            right = [0] * (n + 2)
            for i in range(1, n + 1, 1):
                left[i] = left[i - 1] + nums[i - 1]
            for i in range(n, 0, -1):
                right[i] = right[i + 1] + nums[i - 1]
            for i in range(1, n + 1, 1):
                if left[i - 1] == right[i + 1]:
                    return i - 1
            print(left, right)
            return -1
  • 相关阅读:
    IE 兼容问题笔记
    php编码与解码
    php 一些神奇加有趣的函数
    RESTful 规范
    关于CSS3背景渐变色无效问题
    ECShop
    php中的PHP_EOL换行符
    用 openSSL 生成 公钥 私钥
    app调用支付宝支付 笔记
    utf8 文件 错误保存为gbk 中文乱码 解决方法
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13296761.html
Copyright © 2011-2022 走看看