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
思路:
這道題比較簡單,就是從左周遊到最後記錄并替換最大、第二大數值和索引。
如果有更好的方法請告知,謝謝