Skip to content

Commit e962bc6

Browse files
Merge pull request #1964 from CodingTestStudy2/이진희
[이진희] Day03
2 parents 5a0120e + c15eba4 commit e962bc6

2 files changed

Lines changed: 85 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
3+
1. 아이디어 : k개의 큰수의합와 k개의 작은수의 합을 구해 차이값을 구하기
4+
정렬 후, K번만큼 for문을 돌려 큰수와 작은수의 합을 구하고 빼준다
5+
6+
7+
2. 시간복잡도 : O(NlogN + K)
8+
9+
3. 자료구조/알고리즘 : 계산
10+
11+
*/
12+
13+
class Solution {
14+
public int absDifference(int[] nums, int k) {
15+
// k개의 가장 크고 작은 수
16+
17+
Arrays.sort(nums);
18+
int maxSum = 0;
19+
int minSum = 0;
20+
21+
for(int i=0; i<k; i++) {
22+
maxSum+=nums[nums.length-1-i];
23+
minSum+=nums[i];
24+
}
25+
26+
return maxSum-minSum;
27+
28+
}
29+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
3+
1. 아이디어 : nums1[i]>nums2[i]를 만족하는 최대 원소를 가진 아무 배열 반환
4+
nums1, nums2배열을 정렬후, 투 포인터로 위 조건을 만족하는 최대 원소 배열을 구함
5+
이때 nums2의 원소 위치를 미리 저장해놔야한다.
6+
7+
2. 시간복잡도 : O(2NlogN + N) => O(NlogN)
8+
9+
3. 자료구조/알고리즘 : 투포인터, 커스텀 정렬
10+
11+
*/
12+
13+
class Solution {
14+
public int[] advantageCount(int[] nums1, int[] nums2) {
15+
// 최대한 많은 원소가 nums1[i] > nums2[i]를 만족
16+
17+
// 2 7 11 15
18+
// 8 12 24 32
19+
20+
Arrays.sort(nums1);
21+
List<int[]> nums2Idx = new ArrayList<>();
22+
for(int i=0; i<nums2.length; i++) nums2Idx.add(new int[]{i,nums2[i]});
23+
24+
Collections.sort(nums2Idx, (a,b) ->{
25+
return a[1]-b[1];
26+
});
27+
28+
int[] ans = new int[nums1.length];
29+
30+
// 2 7 11 15
31+
// 1 4 10 11
32+
33+
// 8 12 24 32
34+
// 11 13 25 32
35+
36+
int r = nums2.length-1;
37+
int l = 0;
38+
39+
for(int i=nums2.length-1; i>=0; i--) {
40+
int num = nums2Idx.get(i)[1];
41+
int pos = nums2Idx.get(i)[0];
42+
43+
if(nums1[r]>num) {
44+
ans[pos] = nums1[r];
45+
r--;
46+
}
47+
else {
48+
ans[pos] = nums1[l];
49+
l++;
50+
}
51+
}
52+
53+
return ans;
54+
55+
}
56+
}

0 commit comments

Comments
 (0)