LeetCode - 747. Largest Number At Least Twice of Others(Array, Sorting)

YAMAMAMO·2022년 2월 6일
0

LeetCode

목록 보기
16/100

문제

가장 큰 정수가 고유한 정수 배열 번호가 지정됩니다.
배열에서 가장 큰 요소가 배열의 다른 모든 수보다 두 배 이상 많은지 여부를 확인합니다. 이 경우 가장 큰 요소의 색인을 반환하고, 그렇지 않으면 -1을 반환합니다.

You are given an integer array nums where the largest integer is unique.
Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.

https://leetcode.com/problems/largest-number-at-least-twice-of-others/

Example 1:

Input: nums = [3,6,1,0]
Output: 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.

Example 2:

Input: nums = [1,2,3,4]
Output: -1
Explanation: 4 is less than twice the value of 3, so we return -1.

Example 3:

Input: nums = [1]
Output: 0
Explanation: 1 is trivially at least twice the value as any other number because there are no other numbers.

풀이

자바입니다.

  • 배열의 최대값 위치를 찾습니다.
  • 최대값보다 어느 배열값*2가 크면 -1을 반환합니다.
class Solution {
    public int dominantIndex(int[] nums) {
        if(nums.length==1) return 0;
        
        int maxIndex = 0;
        for(int i=0;i<nums.length;i++){
            if(nums[maxIndex]<nums[i]) maxIndex=i;
        }
        
        for(int i=0;i<nums.length;i++){
            if(i!=maxIndex){
                if(nums[maxIndex]<nums[i]*2) return -1;  
            }
        }
        return maxIndex;
    }
}

단일 루프를 사용하는 방법도 있습니다.
최대값과 두번째 최대값을 찾아 비교하는 방법을 사용하면 됩니다.

profile
안드로이드 개발자

0개의 댓글