[LeetCode] 747. Largest Number At Least Twice of Others

Chobby·2025년 5월 4일
1

LeetCode

목록 보기
399/427

😎풀이

  1. empty: 값과 인덱스가 최하 값인 객체
  2. first: 가장 큰 값과 인덱스를 갖는 객체
  3. second: 두 번째로 큰 값과 인덱스를 갖는 객체
  4. nums 순회
    4-1. first보다 큰 수가 있는 경우, 기존 값을 second로 위임하고 해당 값을 first에 입력
    4-2. first보다 작지만, second보다 큰 값이 있는 경우 second 갱신
  5. second의 값에 2배보다 first의 값이 큰 경우에만 first의 인덱스 반환, 그렇지 못하면 -1 반환
function dominantIndex(nums: number[]): number {
    const empty = {val: -Infinity, index: -Infinity}
    let first = {...empty}
    let second = {...empty}
    for(let i = 0; i < nums.length; i++) {
        const num = nums[i]
        if(num > first.val) {
            second = {...first}
            first.val = num
            first.index = i
        } else if(num > second.val) {
            second.val = num
            second.index = i
        }
    }
    if(first.val >= (second.val * 2)) return first.index
    return -1
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글