Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- Matrix
- Stack
- SQL
- java
- Binary Tree
- simulation
- Method
- Tree
- Number Theory
- Binary Search
- greedy
- implement
- two pointers
- string
- hash table
- Class
- geometry
- 코테
- 파이썬
- Math
- 구현
- database
- array
- dynamic programming
- Counting
- Data Structure
- sorting
- 자바
- bit manipulation
- 코딩테스트
Archives
- Today
- Total
코린이의 소소한 공부노트
[LeetCode/Easy] 169. Majority Element 본문
1. Input
1) int[] nums
2. Output
1) nums의 요소 중 그 개수가 nums의 길이의 절반보다 더 많은 요소를 반환
3. Constraint
1) n == nums.length
2) 1 <= n <= 5 * 10^4
3) -10^9 <= nums[i] <= 10^9
4. Example
Input: nums = [2,2,1,1,1,2,2] -> Output: 2
Input: nums = [3,2,3] -> Output: 3
5. Code
1) 첫 코드(2023/05/13)
class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<>();
for(int i : nums)
map.put(i, map.getOrDefault(i,0)+1);
Iterator it = map.entrySet().iterator();
int ans = 0;
while(it.hasNext()){
Map.Entry e = (Map.Entry)it.next();
if((int)e.getValue()>nums.length/2){
ans = (int)e.getKey();
break;
}
}
return ans;
}
}
2) O(1)으로 못 풀어서 찾아 본 다른 사람의 코드(2023/05/13)
class Solution {
public int majorityElement(int[] nums) {
int majority_index = 0;
int count = 1;
for (int i=1; i < nums.length; i++){
count += nums[i] == nums[majority_index] ? 1 : -1;
if (count == 0){
majority_index = ++i;
count++;
}
}
return nums[majority_index];
}
}
'코딩테스트 풀이 > JAVA' 카테고리의 다른 글
[백준 온라인 저지] 11653. 소인수분해 (0) | 2023.05.16 |
---|---|
[LeetCode/Easy] 206. Reverse Linked List (0) | 2023.05.15 |
[LeetCode/Easy] 145. Binary Tree Postorder Traversal (0) | 2023.05.12 |
[LeetCode/Easy] 144. Binary Tree Preorder Traversal (0) | 2023.05.12 |
[LeetCode/Easy] 119. Pascal's Triangle II (0) | 2023.05.12 |