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. 

提示:

  1. nums 的長度範圍在[1, 50].
  2. 每個 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

思路:

​ 這道題比較簡單,就是從左遍歷到最後記錄並替換最大、第二大數值和索引。

如果有更好的方法請告知,謝謝

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章