Leetcode747至少是其他数字两倍的最大数
Leetcode747至少是其他数字两倍的最大数
在一个给定的数组nums
中,总是存在一个最大元素 。查找数组中的最大元素是否至少是数组中每个其他数字的两倍。如果是,则返回最大元素的索引,否则返回-1。
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.
示例 1:
输入: nums = [3, 6, 1, 0] 输出: 1 解释: 6是最大的整数, 对于数组中的其他整数, 6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1.
示例 2:
输入: nums = [1, 2, 3, 4] 输出: -1 解释: 4没有超过3的两倍大, 所以我们返回 -1.
提示:
-
nums
的长度范围在[1, 50]
. - 每个
nums[i]
的整数范围在[0, 99]
.
java:
class Solution { public int dominantIndex(int[] nums) { int tmp=0,max=0,secondMax=0; for(int i=0;i< nums.length;i++){ if(max<nums[i]){ secondMax=max; max=nums[i]; tmp=i; }else if(secondMax<nums[i]){ secondMax=nums[i]; } } if(max>=secondMax*2){ return tmp; }else { return -1; } } }
python3
class Solution: def dominantIndex(self, nums: List[int]) -> int: """ :type nums:list :return: int """ maxAll=maxSecond=tmp=0 for i in range(len(nums)): if nums[i]>maxAll: maxSecond=maxAll maxAll=nums[i] tmp=i elif maxSecond<nums[i]: maxSecond=nums[i] if maxAll>=maxSecond*2: return tmp return -1
思路:
这道题比较简单,就是从左遍历到最后记录并替换最大、第二大数值和索引。
如果有更好的方法请告知,谢谢

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
Leetcode724:寻找数组的中心索引(java、python3)
寻找数组的中心索引 给定一个整数类型的数组 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]的整数。 起先我的思路是从第一个索引左累加、右累加判断是否想等: import java.util.ArrayList; import java.util.List; import java.util...
- 下一篇
Zabbix4.0 监控http状态码
以下是jenkins服务地址,我要监控下jenkins服务是否正常运行 创建jenkins-status.py脚本,监控http状态返回码 脚本如下 [root@localhost zabbix_agentd.d]# cat /etc/zabbix/zabbix_agentd.d/jenkins-status.py #!/bin/env python # -*- coding: UTF-8 -*- import requests import sys try: html = requests.get("http://192.168.1.118:8080/login") code = html.status_code print(code) except: print(1) sys.exit(0) [root@localhost zabbix_agentd.d]# 执行脚本可以看到jenkins服务的状态返回码为200 [root@localhost zabbix_agentd.d]# ./jenkins-status.py 200 [root@localhost zabbix_agen...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- CentOS关闭SELinux安全模块
- SpringBoot2更换Tomcat为Jetty,小型站点的福音
- CentOS6,CentOS7官方镜像安装Oracle11G
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
- Red5直播服务器,属于Java语言的直播服务器
- CentOS7编译安装Cmake3.16.3,解决mysql等软件编译问题
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- SpringBoot2整合Thymeleaf,官方推荐html解决方案
- CentOS8安装Docker,最新的服务器搭配容器使用
- CentOS7,CentOS8安装Elasticsearch6.8.6