前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode747至少是其他数字两倍的最大数

Leetcode747至少是其他数字两倍的最大数

原创
作者头像
爱写bug
修改2019-05-30 10:03:09
5060
修改2019-05-30 10:03:09
举报
文章被收录于专栏:爱写Bug

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:

代码语言:javascript
复制
输入: nums = [3, 6, 1, 0]
输出: 1
解释: 6是最大的整数, 对于数组中的其他整数,
6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1. 

示例 2:

代码语言:javascript
复制
输入: nums = [1, 2, 3, 4]
输出: -1
解释: 4没有超过3的两倍大, 所以我们返回 -1. 

提示:

  1. nums 的长度范围在[1, 50].
  2. 每个 nums[i] 的整数范围在 [0, 99].

java:

代码语言:javascript
复制
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

代码语言:javascript
复制
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

思路:

​ 这道题比较简单,就是从左遍历到最后记录并替换最大、第二大数值和索引。

如果有更好的方法请告知,谢谢

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Leetcode747至少是其他数字两倍的最大数
    • java:
      • python3
        • 思路:
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档