import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static util.Asserts.assertArrayEquals;
import static util.Asserts.assertNotNull;
/**
* æ ¹æ®æ¯æ¥ æ°æ¸© å表ï¼è¯·éæ°çæä¸ä¸ªå表ï¼å¯¹åºä½ç½®çè¾å
¥æ¯ä½ éè¦åçå¾
å¤ä¹
温度æä¼åé«è¶
è¿è¯¥æ¥ç天æ°ã
* 妿ä¹åé½ä¸ä¼åé«ï¼è¯·å¨è¯¥ä½ç½®ç¨ 0 æ¥ä»£æ¿ã
*
* ä¾å¦ï¼ç»å®ä¸ä¸ªå表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73]ï¼ä½ çè¾åºåºè¯¥æ¯ [1, 1, 4, 2, 1, 1, 0, 0]ã
*
* æç¤ºï¼æ°æ¸© å表é¿åº¦çèå´æ¯ [1, 30000]ãæ¯ä¸ªæ°æ¸©çå¼çåä¸ºåæ°åº¦ï¼é½æ¯å¨ [30, 100] èå´å
çæ´æ°ã
*
*
* æ¥æºï¼åæ£ï¼LeetCodeï¼
* 龿¥ï¼https://leetcode-cn.com/problems/daily-temperatures
* è使å½é¢æ£ç½ç»ææãåä¸è½¬è½½è¯·èç³»å®æ¹ææï¼éåä¸è½¬è½½è¯·æ³¨æåºå¤ã
*
* @author abomb4 2020-01-12
*/
public class Solution739 {
public int[] dailyTemperatures(int[] t) {
// Store temperature and index
final int[] resultList = new int[t.length];
final TreeMap> map = new TreeMap<>();
for (int i = 0; i < t.length; i++) {
final int tem = t[i];
resultList[i] = 0;
final List list = map.get(tem);
if (list == null) {
final LinkedList l = new LinkedList<>();
l.add(i);
map.put(tem, l);
} else {
list.add(i);
}
final Iterator>> it = map.entrySet().iterator();
while (it.hasNext()) {
final Map.Entry> entry = it.next();
final Integer loopTem = entry.getKey();
final List loopIndexes = entry.getValue();
if (tem > loopTem) {
for (final Integer loopIndex : loopIndexes) {
resultList[loopIndex] = i - loopIndex;
}
it.remove();
} else {
break;
}
}
}
return resultList;
}
public static void main(String[] args) {
final Solution739 s = new Solution739();
{
final int[] tst = new int[]{73, 74, 75, 71, 69, 72, 76, 73};
final int[] rst = new int[]{1, 1, 4, 2, 1, 1, 0, 0};
final int[] result = s.dailyTemperatures(tst);
assertNotNull(result, "ç»æ1");
assertArrayEquals(rst, result, "计ç®1");
}
{
final int[] tst = new int[]{89, 62, 70, 58, 47, 47, 46, 76, 100, 70};
final int[] rst = new int[]{8, 1, 5, 4, 3, 2, 1, 1, 0, 0};
final int[] result = s.dailyTemperatures(tst);
assertNotNull(result, "ç»æ2");
assertArrayEquals(rst, result, "计ç®2");
}
System.out.println("OK");
}
}