MCPcopy Create free account
hub / github.com/ROUTINE-STUDY/Algorithm / Sanghoo

Class Sanghoo

LeetCode/Array/169. Majority Element/Sanghoo.java:5–25  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

3import java.util.Arrays;
4
5public class Sanghoo {
6
7 // 리팩토링하며 떠오른 방법
8 // majorityElement > nums.length/2 성질을 생각하다가 발견.. 정렬을 한다면 nums.length/2의 인덱스에 있는 값은 무조건 majorityElement가 아니한가?
9 public static int majorityElement(int[] nums) {
10 int res = 0;
11
12 // 원소가 1개이거나 2개이면 무조건 존재하는 원소가 majorityElement
13 if(nums.length <= 2) return nums[0];
14
15 // 정렬 후 가운데 값은 무조건 최대 원소
16 Arrays.sort(nums);
17 res = nums[nums.length / 2];
18
19 return res;
20 }
21
22 public static void main(String[] args) {
23 System.out.println(majorityElement(new int[]{-1,100,2,100,100,4,100}));
24 }
25}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected