diff --git a/src/main/java/com/vitalish/leetcode/stack/DailyTemperatures.java b/src/main/java/com/vitalish/leetcode/stack/DailyTemperatures.java new file mode 100644 index 0000000..0071c09 --- /dev/null +++ b/src/main/java/com/vitalish/leetcode/stack/DailyTemperatures.java @@ -0,0 +1,46 @@ +package com.vitalish.leetcode.stack; + +import java.util.Stack; + +/** + * Daily Temperatures + * + * @see https://neetcode.io/problems/daily-temperatures + */ +public class DailyTemperatures { + + // 0(n^2) + public int[] dailyTemperatures(int[] temperatures) { + int[] result = new int[temperatures.length]; + + for (int i = 0; i < temperatures.length; i++) { + int j = i; + int daysCount = 0; + while (j < temperatures.length && temperatures[i] >= temperatures[j]) { + daysCount++; + j++; + } + if (j == temperatures.length) { + result[i] = 0; + } else { + result[i] = daysCount; + } + } + return result; + } + + // O(n) + public int[] dailyTemperatures2(int[] temperatures) { + int[] result = new int[temperatures.length]; + Stack stack = new Stack<>(); + + for (int i = 0; i < temperatures.length; i++) { + while (!stack.empty() && temperatures[i] > temperatures[stack.peek()]) { + int j = stack.pop(); + result[j] = i - j; + } + stack.push(i); + } + return result; + } +} diff --git a/src/test/java/com/vitalish/leetcode/stack/DailyTemperaturesTest.java b/src/test/java/com/vitalish/leetcode/stack/DailyTemperaturesTest.java new file mode 100644 index 0000000..159549d --- /dev/null +++ b/src/test/java/com/vitalish/leetcode/stack/DailyTemperaturesTest.java @@ -0,0 +1,34 @@ +package com.vitalish.leetcode.stack; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +class DailyTemperaturesTest { + + private final DailyTemperatures dailyTemperatures = new DailyTemperatures(); + + @ParameterizedTest + @MethodSource("arguments") + void calcDailyTemperatures(int[] temperatures, int[] expectedResult) { + assertArrayEquals(expectedResult, dailyTemperatures.dailyTemperatures(temperatures)); + } + + @ParameterizedTest + @MethodSource("arguments") + void calcDailyTemperatures2(int[] temperatures, int[] expectedResult) { + assertArrayEquals(expectedResult, dailyTemperatures.dailyTemperatures2(temperatures)); + } + + + private static Stream arguments() { + return Stream.of( + Arguments.of(new int[]{30, 38, 30, 36, 35, 40, 28}, new int[]{1, 4, 1, 2, 1, 0, 0}), + Arguments.of(new int[]{22, 21, 20}, new int[]{0, 0, 0}) + ); + } +} \ No newline at end of file