Replies: 4 comments
📌 캐시
import java.util.*;
class Solution {
public int solution(int cacheSize, String[] cities) {
if (cacheSize == 0) {
return cities.length * 5;
}
for (int i = 0; i < cities.length; i++) {
cities[i] = cities[i].toUpperCase();
}
List<String> cacheList = new LinkedList<>();
int time = 0;
for (int i = 0; i < cities.length; i++) {
// cacheList가 비어있지않고 다 차지않은 경우
if (cacheList.size() < cacheSize && !cacheList.isEmpty()) {
if (cacheList.contains(cities[i])) {
time += 1;
cacheList.remove(cities[i]);
cacheList.add(cities[i]);
} else {
time += 5;
cacheList.add(cities[i]);
}
} else if (cacheList.isEmpty()) { // cacheList가 비어있는 경우
time += 5;
cacheList.add(cities[i]);
} else if (cacheList.size() == cacheSize) { // cacheList가 다 찬 경우
if (cacheList.contains(cities[i])) {
time += 1;
cacheList.remove(cities[i]);
cacheList.add(cities[i]);
} else {
time += 5;
cacheList.remove(0);
cacheList.add(cities[i]);
}
}
}
return time;
}
}
import java.util.*;
class Solution {
public int solution(int cacheSize, String[] cities) {
if (cacheSize == 0) {
return cities.length * 5;
}
for (int i = 0; i < cities.length; i++) {
cities[i] = cities[i].toUpperCase();
}
Queue<String> cacheQueue = new LinkedList<>();
int time = 0;
for (int i = 0; i < cities.length; i++) {
String city = cities[i];
if (cacheQueue.contains(city)) {
cacheQueue.remove(city);
cacheQueue.add(city);
time += 1;
} else {
if (cacheQueue.size() == cacheSize) {
cacheQueue.poll();
}
cacheQueue.add(city);
time += 5;
}
}
return time;
}
}📌 이모티콘 할인 행사
class Solution {
public int[] solution(int[][] users, int[] emoticons) {
int[] discount = {10, 20, 30, 40};
int[] emoticonDiscount = new int[emoticons.length];
return dfs(discount, emoticonDiscount, users, emoticons, 0);
}
private static int[] dfs(int[] discount, int[] emoticonDiscount, int[][] users, int[] emoticons, int count) {
if (count == emoticons.length) {
int joinCount = 0; // 이모티콘 플러스 서비스 가입 수
int totalPrice = 0; // 이모티콘 매출액
for (int i = 0; i < users.length; i++) {
int minRate = users[i][0];
int money = users[i][1];
int price = 0;
for (int j = 0; j < emoticons.length; j++) {
if (emoticonDiscount[j] >= minRate) {
price += emoticons[j] * (100 - emoticonDiscount[j]) / 100;
}
}
if (price >= money) {
joinCount++;
} else {
totalPrice += price;
}
}
return new int[] {joinCount, totalPrice};
}
int[] answer = {0, 0};
for (int rate : discount) {
emoticonDiscount[count] = rate;
int[] result = dfs(discount, emoticonDiscount, users, emoticons, count + 1);
answer = max(answer, result);
}
return answer;
}
private static int[] max(int[] answer, int[] result) {
if (result[0] > answer[0]) {
return result;
} else if (answer[0] == result[0] && result[1] > answer[1]) {
return result;
}
return answer;
}
} |
0 replies
🗂 [1차] 캐시[ 시간 복잡도 ]
[ 캐시 처리 주의 ]
반례 예시
class Solution {
public int solution(int cacheSize, String[] cities) {
List<String> list = new ArrayList<>();
// 예외
if(cacheSize == 0){
return cities.length * 5;
}
int count = 0;
for(int i = 0; i < cities.length; i++){
String city = cities[i].toLowerCase();
// 캐시O: 1점 + 캐시 데이터 제거
// 캐시X: 5점
if(list.contains(city)){
count += 1;
list.remove(city);
} else {
count += 5;
}
// 캐시가 가득찬 경우 맨앞 데이터 제거
if(list.size() == cacheSize){
list.remove(0);
}
list.add(city);
}
return count;
}
}[ 이모티콘 할인 행사 ] 😎💡 접근 방법
public class EmoticonSales2 {
private static final int[] DISCOUNT_PERCENT = {10, 20, 30, 40};
private static int[] remember;
private static int[] emoticons;
private static int[][] users;
private static List<Result> results;
public int[] solution2(int[][] users, int[] emoticons) {
this.emoticons = emoticons;
this.users = users;
this.remember = new int[emoticons.length];
this.results = new ArrayList<>();
dfs(0, emoticons.length);
results.sort(Comparator.naturalOrder());
Result result = results.get(0);
return new int[]{result.purchaseCount, result.totalPrice};
}
private static void dfs(int depth, int targetDepth) {
if (depth == targetDepth) {
// 이모티콘 구매
results.add(getPurchaseResult());
return;
}
for (int i = 0; i < DISCOUNT_PERCENT.length; i++) {
remember[depth] = DISCOUNT_PERCENT[i];
dfs(depth + 1, targetDepth);
}
}
private static Result getPurchaseResult() {
int purchaseCount = 0;
int resultPrice = 0;
// 사람들 순회
for (int row = 0; row < users.length; row++) {
int totalPrice = 0;
int percent = users[row][0];
int plusPrice = users[row][1];
// 이모티콘 구매 결정
for (int index = 0; index < emoticons.length; index++) {
int discountPercent = remember[index];
int basicPrice = emoticons[index];
// 구매 하는 이모티콘 할인 비율이라면
if (discountPercent >= percent) {
int discountPrice = (int) (basicPrice * (100 - discountPercent) * 0.01);
totalPrice += discountPrice;
}
// 플러스 구매 가능하면 이모티콘 구매 중단
if (totalPrice >= plusPrice) {
purchaseCount++;
totalPrice = 0;
break;
}
}
// 구매 비용 누적
resultPrice += totalPrice;
}
return new Result(purchaseCount, resultPrice);
}
static class Result implements Comparable<Result> {
private int purchaseCount;
private int totalPrice;
public Result(int purchaseCount, int totalPrice) {
this.purchaseCount = purchaseCount;
this.totalPrice = totalPrice;
}
public int compareTo(Result another) {
int result = another.purchaseCount - this.purchaseCount;
if (result != 0) return result;
return another.totalPrice - this.totalPrice;
}
}
} |
0 replies
1️⃣ [1차] 캐시
function solution(cacheSize, cities) {
let cache = [];
let time = 0;
for(let city of cities) {
city = city.toLowerCase(); // 대소문자 구분 x - 소문자로 처리
if(cache.includes(city)) {
// 캐시 히트
time += 1;
cache = cache.filter(c => c !== city); // 기존 위치 제거
cache.push(city); // 맨 뒤로 추가
} else {
// 캐시 미스
time += 5;
cache.push(city);
if(cache.length > cacheSize) { // 오래된 거 제거
cache.shift();
}
}
}
return time;
} |
0 replies
캐시해결 방법
import java.util.*;
class Solution {
public int solution(int cacheSize, String[] cities) {
// 총 실행 시간
int time = 0;
// 캐시를 저장할 리스트
List<String> cache = new ArrayList<>();
// 도시 하나씩 처리
for (int i = 0; i < cities.length; i++) {
String city = cities[i].toLowerCase(); // 대소문자 구분 X
// 캐시에 있는 경우 -> hit
if (cache.contains(city)) {
cache.remove(city); // 위치 제거
cache.add(city); // 가장 최근 사용 -> 맨 뒤로
time += 1; // hit는 시간 +1
}
// 캐시에 없는 경우 -> miss
else {
time += 5; // miss는 시간 +5
// 캐시가 가득 찼다면, 가장 오래된 거 제거 (맨 앞)
if (cacheSize > 0 && cache.size() == cacheSize) {
cache.remove(0); // 제일 앞에 있는 게 가장 오래됨
}
// 캐시 크기가 0이 아닐 경우만 추가
if (cacheSize > 0) {
cache.add(city); // 새 도시 추가
}
}
}
return time;
}
}이모티콘 할인 행사해결방법
|
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
📢 이번 주 알고리즘 스터디 문제
이번 주에는 총 4문제를 풉니다.
(정답률은 프로그래머스 기준)
📌 문제 목록 [ 2단계 ]
🗓️ 발표
🚨 벌금 규칙
🔥 이번 주도 화이팅입니다!
All reactions