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
- 알고리즘
- 투어
- 양꼬치
- Servlet
- 문자열 압축
- BFS
- 2638
- 호유동
- 다이나믹 프로그래밍
- 완도산회
- 백준
- 2020 KAKAO BLIND
- 동적 프로그래밍
- 설탕 배달
- 1로 만들기
- 맛집
- 2839
- mvc
- 프로그래머스
- 쓰레드 풀
- HTTP API
- 포두부 보쌈
- dp
- 맛집 투어
- 고모네 콩탕
- 스프링 MVC
- 2589
- 스프링
- 서블릿
- Spring
Archives
- Today
- Total
프로그래밍 공방
[LeetCode] Median of Two Sorted Arrays 본문
문제
leetcode.com/problems/median-of-two-sorted-arrays/
Median of Two Sorted Arrays - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제해결방법
이 문제는 정렬된 두 배열이 주어지고 두 배열을 합쳤을때 중앙값을 구하는 문제였다.
각 배열에 시작 인덱스를 두고 각 배열의 원소들을 앞에서부터 비교해가면서 두 배열을 합친 길이의 중간 개수까지 세준다.
코드
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | package leetcode; public class Solution_MedianofTwoSortedArrays { public static double findMedianSortedArrays(int[] nums1, int[] nums2) { int N = nums1.length; int M = nums2.length; int i1 = 0, i2 = 0; int count = 0; int index = (M+N)>>1; double mid = 0; if((N+M)%2==0) index--; while(count<=index) { if(i1<nums1.length && i2<nums2.length) { if(nums1[i1]<nums2[i2]) { mid = nums1[i1]; i1++; } else { mid = nums2[i2]; i2++; } } else if(i1>=nums1.length && i2<nums2.length) { mid = nums2[i2]; i2++; } else if (i1<nums1.length && i2>=nums2.length) { mid = nums1[i1]; i1++; } count++; } if((N+M)%2==0) { if(i1<nums1.length && i2<nums2.length) { if(nums1[i1]<nums2[i2]) mid += nums1[i1]; else mid += nums2[i2]; } else if(i1>=nums1.length && i2<nums2.length) mid += nums2[i2]; else if (i1<nums1.length && i2>=nums2.length) mid += nums1[i1]; mid /= 2.0d; } return mid; } public static void main(String[] args) { int[] nums1 = {}; int[] nums2 = {1}; System.out.println(findMedianSortedArrays(nums1, nums2)); } } | cs |
코드에 대한 피드백이나 더 좋은 아이디어는 언제나 환영입니다.
'개발 > 문제해결' 카테고리의 다른 글
[프로그래머스] 프렌즈4블록 (0) | 2021.01.05 |
---|---|
[프로그래머스] 지형 이동 (0) | 2021.01.02 |
[백준] 2156번 : 포도주 시식 (0) | 2021.01.01 |
[프로그래머스] 뉴스 클러스터링 (0) | 2020.12.30 |
[프로그래머스] 비밀지도 (0) | 2020.12.30 |