[LeetCode] 169. Majority Element

lkdcode·2023년 8월 24일

Algorithm

목록 보기
6/47
post-thumbnail

169. Majority Element


문제 분석

주어진 배열에서 가장 많이 등장하는 숫자를 리턴하는 문제


풀이 과정

배열을 정렬한 후 반복문을 돈다.
현재의 값과 다음의 값이 다르다면 반복문을 종료하고
그게 아니라면 카운트를 1 올려준다.
올려진 카운트는 정답에 업데이트해준다. 업데이트할 때는
기존의 값과 비교하여 더 큰 값으로 업데이트 해준다.


코드

    public int majorityElement(int[] nums) {
        Arrays.sort(nums);

        int maxCount = -1;
        int result = 0;

        for (int i = 0; i < nums.length; i++) {
            int n = nums[i];
            int newCount = 0;

            for (int j = i + 1; j < nums.length; j++) {
                if (n != nums[j]) {
                    break;
                }
                newCount++;
            }

            if (maxCount < newCount) {
                maxCount = newCount;
                result = n;
            }

            i += newCount;
        }

        return result;
    }

profile
되면 한다

0개의 댓글