博客
关于我
pivotIndex-寻找数组的中心索引
阅读量:666 次
发布时间:2019-03-15

本文共 1036 字,大约阅读时间需要 3 分钟。

题意

给定一个整数类型的数组 nums,请编写一个能够返回数组 “中心索引” 的方法。

我们是这样定义数组 中心索引 的:数组中心索引的左侧所有元素相加的和等于右侧所有元素相加的和。

如果数组不存在中心索引,那么我们应该返回 -1。如果数组有多个中心索引,那么我们应该返回最靠近左边的那一个。

示例 1:

输入:

nums = [1, 7, 3, 6, 5, 6]
输出:3
解释:
索引 3 (nums[3] = 6) 的左侧数之和 (1 + 7 + 3 = 11),与右侧数之和 (5 + 6 = 11) 相等。
同时, 3 也是第一个符合要求的中心索引。

示例 2:

输入:

nums = [1, 2, 3]
输出:-1
解释:
数组中不存在满足此条件的中心索引。

说明:

nums 的长度范围为 [0, 10000]。

任何一个 nums[i] 将会是一个范围在 [-1000, 1000]的整数。

解题思路

1.求出整个数组的和

2.只要按顺序累计和出来,累计和*2是步骤1的结果-减去当前数组元素即可
3.不符合步骤2,超出数组长度返回-1;

解题代码:

class Solution {       public int pivotIndex(int[] nums) {           if(nums.length==0)            return -1; //首先计算数组全部的值        int sum=0;        for (int i = 0; i < nums.length; i++) {               sum+=nums[i];        }        int asum=0;        for (int i = 0; i < nums.length; i++) {               if(asum*2==sum-nums[i])                return i;            /*if(asum*2>sum-nums[i])                return -1;*/            asum+=nums[i];        }        return -1;    }}

效果

info		解答成功:		执行耗时:2 ms,击败了55.66% 的Java用户		内存消耗:39.3 MB,击败了27.92% 的Java用户

转载地址:http://vejmz.baihongyu.com/

你可能感兴趣的文章
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>