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 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: 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.

     [暴力解法]:

    leftsum, rightsum都用for循环来求

    时间分析:n+n

    空间分析:

     [优化后]:求leftsum, 剩下的用减法判断sum - nums[i] - leftsum 是否等于leftsum 

    时间分析:n+1

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    还是要有点自信的,有时候真的就只能用暴力解法

    [一句话思路]:

    不嵌套 一次只加一个数、化加法为减法,降低时间复杂度

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 提前标注一下特殊的 不是i的 边界值:leftsum只加到了i - 1

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    不嵌套 一次只加一个数、化加法为减法,降低时间复杂度

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [关键模板化代码]:

    降低复杂度:

    for (int i = 0; i < nums.length; i++) {
                if (i != 0) leftsum += nums[i - 1];
                if ((sum - leftsum - nums[i]) == leftsum) return i;
            }

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public int pivotIndex(int[] nums) {
            //cc
            if (nums == null || nums.length == 0) {
                return -1;
            }
            
            //ini
            int leftsum = 0, sum = 0;
            for (int i = 0; i < nums.length; i++) {
                sum += nums[i];
            }
            
            //for loop, leftsum to i - 1, deduce
            for (int i = 0; i < nums.length; i++) {
                if (i != 0) leftsum += nums[i - 1];
                if ((sum - leftsum - nums[i]) == leftsum) return i;
            }
            
            return -1;
        }
    }
    View Code
  • 相关阅读:
    solr schema.xml配置
    solrconfig.xml配置文件
    solr 使用edismax来控制评分
    solr 打分和排序机制(转载)
    VMware vCenter Converter Standalone使用,物理机转换虚拟机
    Windows server开机登录取消按ctrl+alt+delete组合键
    pycharm专业版2020.1.1版本最新亲测激活,其他版本也复用
    jmeter服务器监控和插件管理
    windows下安装navicat15破解,详解最全
    linux解压汉字文件是乱码
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8908215.html
Copyright © 2011-2022 走看看