Majority Element

bong bong·2023년 8월 25일

알고리즘

목록 보기
25/31

배열중 가장 많은 숫자를 꺼낸다.
배열을 앞에서부터 하나씩 꺼내는데 count를 올려준다. 가장 많이 나온 값을 varyfavorit 변수에 담아준다.

nums크기 배열이 주어지면 대부분의 요소를n 반환합니다 .

다수의 요소는 2회 이상 나타나는 요소입니다 ⌊n / 2⌋. 대부분의 요소가 배열에 항상 존재한다고 가정할 수 있습니다.

class Solution {
public int majorityElement(int[] nums) {
int varyfavorit = nums[0];

    int count = 1; 
    for(int i = 1; i< nums.length; i++){
        if(nums[i]== varyfavorit){
            count++;
        }else if(count >0){
            count --;
        }
        else{
            varyfavorit = nums[i];
            count = 1;
        }
    }
    return varyfavorit;
}

}

profile
let's go invent tomorrow rather than worrying about what happened yesterday - Steven Paul Jobs

0개의 댓글