代码随想录算法训练营 Day 58 | 739.每日温度,496.下一个更大元素Ⅰ

739.每日温度

讲解链接:代码随想录-739.每日温度

public int[] dailyTemperatures(int[] temperatures) {
    int len = temperatures.length;
    int[] answer = new int[len];
    Deque<Integer> stack = new LinkedList<>();
    for (int i = 0; i < len; i++) {
        while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
            answer[stack.peek()] = i - stack.peek();
            stack.pop();
        }
        stack.push(i);
    }

    return answer;
}

496.下一个更大元素Ⅰ

讲解链接:代码随想录-496.下一个更大元素Ⅰ

单调栈
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
    Deque<Integer> stack = new LinkedList<>();
    int[] ans = new int[nums1.length];
    Arrays.fill(ans, -1);
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums1.length; i++) {
        map.put(nums1[i], i);
    }
    for (int i = 0; i < nums2.length; i++) {
        while (!stack.isEmpty() && nums2[stack.peek()] < nums2[i]) {
            int pre = nums2[stack.pop()];
            if (map.containsKey(pre)) {
                ans[map.get(pre)] = nums2[i];
            }
        }
        stack.push(i);
    }

    return ans;
}
暴力破解
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
    int[] ans = new int[nums1.length];

    for (int i = 0; i < nums1.length; i++) {
        int nextMax = -1;
        boolean exist = false;
        for (int j = 0; j < nums2.length; j++) {
            if (nums1[i] == nums2[j]) exist = true;
            if (nums1[i] < nums2[j] && exist) {
                nextMax = nums2[j];
                break;
            }
        }
        ans[i] = nextMax;
    }
    return ans;
}

你可能感兴趣的:(算法)