기본틀 :
using System;
public class Solution {
public int solution(int[] ingredient) {
int answer = 0;
return answer;
}
}
문제를 보고 먼저 든 생각이 '어떤 자료형을 쓰지?' 였다.
문제를 보면 Stack아니면 List를 사용하면 풀 수 있을거라는 생각했기 때문이다.
결국 나는 Stack은 stack[index] 와 같이 index를 통해 뭔가를 조회하기 안 되기 때문에
List를 사용하기로 결정했다.
먼저, int 형 배열 canMake를 선언과 동시에 {1, 2, 3, 1}로 할당 및 int 형 자료 count와 List를 만들어준다.
그 다음 ingredient를 반복문으로 순회하면서 List에 요소를 담는데
list의 개수가 4이상 즉, 햄버거를 만들 수 있는 수 이면
새로운 배열에 현재 list에 있는 재료들을 새로운 배열에 복사해준다.
그 후, canMake와 재료들의 순서가 같으면
list에서 해당 자료들을 제거하고 count를 증가시켜줬다.
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public int solution(int[] ingredient) {
int[] canMake = new int[] {1,2,3,1};
int count = 0;
List<int> list = new List<int>();
for(int i =0; i < ingredient.Length; i++)
{
list.Add(ingredient[i]);
if(list.Count >= 4)
{
int[] makeTry = { list[list.Count - 4], list[list.Count - 3], list[list.Count - 2], list[list.Count - 1] };
if(canMake.SequenceEqual(makeTry))
{
list.RemoveRange(list.Count - 4, 4);
count++;
}
}
}
return count;
}
}
SequenceEqual 함수는
int[] array1 = { 1, 2, 3 };
int[] array2 = { 1, 2, 3 };
int[] array3 = { 1, 2, 4 };
Console.WriteLine(array1.SequenceEqual(array2)); // true
Console.WriteLine(array1.SequenceEqual(array3)); // false
List<string> list1 = new List<string> { "apple", "banana", "cherry" };
List<string> list2 = new List<string> { "apple", "banana", "cherry" };
List<string> list3 = new List<string> { "apple", "cherry", "banana" };
Console.WriteLine(list1.SequenceEqual(list2)); // true
Console.WriteLine(list1.SequenceEqual(list3)); // false (순서가 다름)
배열이나 list에서 요소의 순서와 요소가 동일해야만 true, 아닐 경우 false를 반환해주는 함수
'문제 풀기 > C#' 카테고리의 다른 글
70. 바탕화면 정리 (0) | 2025.02.19 |
---|---|
69. 성격 유형 검사하기 (0) | 2025.02.19 |
67. 둘만의 암호 (0) | 2025.02.18 |
66. 대충 만든 자판(Dictionary) (0) | 2025.02.18 |
65. 문자열 나누기 (0) | 2025.02.12 |