Skip to content

Commit

Permalink
Daily Temperatures
Browse files Browse the repository at this point in the history
  • Loading branch information
vitalish committed Nov 12, 2024
1 parent 09bdf91 commit 37d2c60
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/main/java/com/vitalish/leetcode/stack/DailyTemperatures.java
Original file line number Diff line number Diff line change
@@ -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<Integer> 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;
}
}
Original file line number Diff line number Diff line change
@@ -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> 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})
);
}
}

0 comments on commit 37d2c60

Please sign in to comment.