Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3] Output: 3
Example 2:
Input: [2,2,1,1,1,2,2] Output: 2
문제 풀이:
난이도 easy
처음에 맵을 써서 풀었는데 그것보다 더 쉬운 방법이 있었다...! 소팅한 다음 중간에 위치한 값을 리턴하면 됐다..
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 160] Intersection of Two Linked Lists (0) | 2020.11.02 |
---|---|
[leetcode 155] Min Stack (0) | 2020.11.01 |
[leetcode 236] Lowest Common Ancestor of a Binary Tree (0) | 2020.10.31 |
[leetcode 238] Product of Array Except Self (0) | 2020.10.31 |
[leetcode 234] Palindrome Linked List (0) | 2020.10.31 |
댓글