반응형
문제
Kids With the Greatest Number of Candies - LeetCode
문제 해결 방법
- 알고리즘
- 일단 주어진 어레이에서 max값을 찾는다
- 각 어레이를 순회하며, 추가 사탕을 더한값이 max값보다 크면 true를 작으면 false를 추가한다.
- stream을 사용하는것은 추천하지 않습니다. 복잡한 요소가 있는것이 아니기때문에 단순한 advanced for문 정도면 충분합니다.
- if(candy + extraCandies < max)에서 candy + extraCandies를 따로 가로안에 넣어줄 필요도 없습니다. 자바 우선순위에 따라 필요하지 않습니다.
- if문은 물음표 연산자로 대체 가능합니다.
if(candy+extraCandies<max) result.add(false);
else result.add(true);
참고
Github Link
https://github.com/eunhanlee/LeetCode_1431_KidsWiththeGreatestNumberofCandies_Solution.git
시간복잡도: O(n), 공간복잡도: O(n)
/**
* 추가된 사탕을 고려하여 각 아이가 최대 사탕을 가질 수 있는지 여부를 결정합니다.
*
* @param candies 각 아이가 가지고 있는 사탕의 수를 나타내는 정수 배열
* @param extraCandies 각 아이가 추가로 가질 수 있는 사탕의 수
* @return 각 아이가 최대 사탕을 가질 수 있는지 여부를 나타내는 불리언 값들로 이루어진 리스트
*/
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
// 주어진 배열에서 최대 사탕의 수를 찾습니다.
int max = 0;
for (int candy : candies) {
max = Math.max(max, candy);
}
// 각 아이가 최대 사탕을 가질 수 있는지 확인합니다.
List<Boolean> result = new ArrayList<>(candies.length);
for (int candy : candies) {
// 해당 아이가 추가된 사탕을 더했을 때 최대 사탕의 수보다 작으면 최대 사탕을 가질 수 없는 것으로 간주합니다.
result.add(!(candy + extraCandies >= max));
}
return result;
}
반응형
'old > Algorithm Solving' 카테고리의 다른 글
LeetCode 2235. Add Two Integers 자바 문제 풀이 (0) | 2023.08.05 |
---|---|
LeetCode 1512. Number of Good Pairs 자바 문제 풀이 (0) | 2023.08.05 |
LeetCode 217. Contains Duplicate 자바 문제 풀이 (0) | 2023.08.04 |
LeetCode 42. Trapping Rain Water 자바 문제 풀이 (0) | 2023.08.03 |
LeetCode 771. Jewels and Stones 자바 문제 풀이 (0) | 2023.08.02 |