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

JAVA代码编写

739. 每日温度

给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。

示例 1:

输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]

示例 2:

输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]

示例 3:

输入: temperatures = [30,60,90]
输出: [1,1,0]

提示:

  • 1 <= temperatures.length <= 105
  • 30 <= temperatures[i] <= 100

教程:https://programmercarl.com/0739.%E6%AF%8F%E6%97%A5%E6%B8%A9%E5%BA%A6.html

方法一:暴力解法

思路:两个for循环,第一个循环遍历temperatures数组当前i下标,第二哥循环遍历右指针,旨在找到比i大的下标j,找到就将j-i加入数组,当j走完也没找到的话,就将0加入数组。循环走完,其实没算最后一个温度的下一个,最后一个都是0,再向数组中加一下。

力扣中超出时间限制。

复杂度分析

  • 时间复杂度: O ( n 2 ) O(n^2) O(n2)
  • 空间复杂度: O ( n ) O(n) O(n)
import java.util.ArrayList;
import java.util.List;

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < temperatures.length; i++) {// 当前要遍历的数
            for (int j = i+1; j < temperatures.length; j++) {// 比i大的下标j
                if(temperatures[i]<temperatures[j]){// 找到就添加,并结束本次循环,找下一个i
                    res.add(j-i);
                    break;
                }else if(j==temperatures.length-1){// 遍历到最后,还没有找到比当前i大的就加0
                    res.add(0);
                }
            }
        }
        res.add(0); // 最后一个都是0
        // 将List res 转为int[]
        int[] a = new int[res.size()];
        for (int i = 0; i < res.size(); i++) {
            a[i] = res.get(i);
        }
        return a;
    }
    
    public static void main(String[] args) {
        Solution solution = new Solution();
//        solution.dailyTemperatures(new int[]{73,74,75,71,69,72,76,73});
        solution.dailyTemperatures(new int[]{30,60,90});
    }
}

这个和上面的一样,就是结果直接用的int[]存的

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        
        int[] res = new int[temperatures.length];
        for (int i = 0; i < temperatures.length; i++) {// 当前要遍历的数
            for (int j = i+1; j < temperatures.length; j++) {// 比i大的下标j
                if(temperatures[i]<temperatures[j]){// 找到就添加,并结束本次循环,找下一个i
                    res[i]=j-i;
                    break;
                }else if(j==temperatures.length-1){// 遍历到最后,还没有找到比当前i大的就加0
                    res[i]=0;
                }
            }
        }
        res[res.length-1]=0; // 最后一个都是0
        return res;
    }
}

代码简洁版:因为数组默认就是0

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        
        int[] res = new int[temperatures.length];
        for (int i = 0; i < temperatures.length; i++) {// 当前要遍历的数
            for (int j = i+1; j < temperatures.length; j++) {// 比i大的下标j
                if(temperatures[i]<temperatures[j]){// 找到就添加,并结束本次循环,找下一个i
                    res[i]=j-i;
                    break;
                }
            }
        }
        return res;
    }
}

方法二:单调栈

思路通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,此时我们就要想到可以用单调栈。时间复杂度为O(n)。

单调栈的本质是空间换时间,因为在遍历的过程中需要用一个栈来记录右边第一个比当前元素高的元素,优点是整个数组只需要遍历一次。

使用单调栈主要有三个判断条件。

  • 当前遍历的元素T[i]小于栈顶元素T[st.top()]的情况
  • 当前遍历的元素T[i]等于栈顶元素T[st.top()]的情况
  • 当前遍历的元素T[i]大于栈顶元素T[st.top()]的情况

复杂度分析

  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( n ) O(n) O(n)
import java.util.Deque;
import java.util.LinkedList;

class Solution {
    // 版本 1
    public int[] dailyTemperatures(int[] temperatures) {

        int lens=temperatures.length;
        int []res=new int[lens];

        /**
         如果当前遍历的元素 大于栈顶元素,表示 栈顶元素的 右边的最大的元素就是 当前遍历的元素,
         所以弹出 栈顶元素,并记录
         如果栈不空的话,还要考虑新的栈顶与当前元素的大小关系
         否则的话,可以直接入栈。
         注意,单调栈里 加入的元素是 下标。
         */
        Deque<Integer> stack=new LinkedList<>();
        stack.push(0);// 先将索引0压入栈
        for(int i=1;i<lens;i++){
            if(temperatures[i]<=temperatures[stack.peek()]){
                stack.push(i);
            }else{
                while(!stack.isEmpty()&&temperatures[i]>temperatures[stack.peek()]){
                    res[stack.peek()]=i-stack.peek();
                    stack.pop();
                }
                stack.push(i);
            }
        }

        return  res;
    }
    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.dailyTemperatures(new int[]{73,74,75,71,69,72,76,73});
//        solution.dailyTemperatures(new int[]{30,60,90});
    }
}

stack.peek() 表示栈顶元素,即获取栈中当前最顶部的元素而不移除它。

stack.pop() 方法表示将栈顶的元素从栈中移除,并返回被移除的元素。

简洁版

import java.util.Stack;

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] res = new int[n];
        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                int idx = stack.pop();
                res[idx] = i - idx;
            }
            stack.push(i);
        }

        return res;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] result = solution.dailyTemperatures(new int[]{73,74,75,71,69,72,76,73});
        for (int num : result) {
            System.out.print(num + " ");
        }
    }
}

496.下一个更大元素 I

nums1 中数字 x下一个更大元素 是指 xnums2 中对应位置 右侧第一个x 大的元素。

给你两个 没有重复元素 的数组 nums1nums2 ,下标从 0 开始计数,其中nums1nums2 的子集。

对于每个 0 <= i < nums1.length ,找出满足 nums1[i] == nums2[j] 的下标 j ,并且在 nums2 确定 nums2[j]下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1

返回一个长度为 nums1.length 的数组 ans 作为答案,满足 ans[i] 是如上所述的 下一个更大元素

示例 1:

输入:nums1 = [4,1,2], nums2 = [1,3,4,2].
输出:[-1,3,-1]
解释:nums1 中每个值的下一个更大元素如下所述:
- 4 ,用加粗斜体标识,nums2 = [1,3,4,2]。不存在下一个更大元素,所以答案是 -1 。
- 1 ,用加粗斜体标识,nums2 = [1,3,4,2]。下一个更大元素是 3 。
- 2 ,用加粗斜体标识,nums2 = [1,3,4,2]。不存在下一个更大元素,所以答案是 -1 。

示例 2:

输入:nums1 = [2,4], nums2 = [1,2,3,4].
输出:[3,-1]
解释:nums1 中每个值的下一个更大元素如下所述:
- 2 ,用加粗斜体标识,nums2 = [1,2,3,4]。下一个更大元素是 3 。
- 4 ,用加粗斜体标识,nums2 = [1,2,3,4]。不存在下一个更大元素,所以答案是 -1 。

提示:

  • 1 <= nums1.length <= nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 104
  • nums1nums2中所有整数 互不相同
  • nums1 中的所有整数同样出现在 nums2

**进阶:**你可以设计一个时间复杂度为 O(nums1.length + nums2.length) 的解决方案吗?

教程:https://programmercarl.com/0496.%E4%B8%8B%E4%B8%80%E4%B8%AA%E6%9B%B4%E5%A4%A7%E5%85%83%E7%B4%A0I.html

方法一:暴力解法

思路:定义一个数组,长度为nums1的长度,默认值设置为-1,初始默认不存在下一个更大元素。

然后从nums2中找到nums1[i]的位置,接着在nums2中找到nums1[i]后,再找其右侧的下一个更大元素。

这个在力扣上可以通过。

复杂度分析

  • 时间复杂度: O ( n 2 ) O(n^2) O(n2)
  • 空间复杂度: O ( n ) O(n) O(n)
class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] res = new int[nums1.length];

        for (int i = 0; i < nums1.length; i++) {
            res[i] = -1; // 设置默认值为 -1

            // 从nums2中找到nums1[i]的位置
            int index = -1;
            for (int j = 0; j < nums2.length; j++) {
                if (nums2[j] == nums1[i]) {
                    index = j;
                    break;
                }
            }

            // 在nums2中找到nums1[i]后,再找其右侧的下一个更大元素
            for (int j = index + 1; j < nums2.length; j++) {
                if (nums2[j] > nums1[i]) {
                    res[i] = nums2[j];
                    break;
                }
            }
        }

        return res;
    }
}

方法二:单调栈

思路:和方法一一样,定义一个数组,填充为-1。将nums的值和索引填到hashmap中,方便查找。

代码整体和739. 每日温度一样,就是添加一个在hashmap中查找的条件。

复杂度分析

  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( n ) O(n) O(n)
class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Stack<Integer> temp = new Stack<>();
        int[] res = new int[nums1.length];
        Arrays.fill(res,-1);
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0 ; i< nums1.length ; i++){
            hashMap.put(nums1[i],i);
        }
        temp.add(0);
        for (int i = 1; i < nums2.length; i++) {
            if (nums2[i] <= nums2[temp.peek()]) {
                temp.add(i);
            } else {
                while (!temp.isEmpty() && nums2[temp.peek()] < nums2[i]) {
                    if (hashMap.containsKey(nums2[temp.peek()])){
                        Integer index = hashMap.get(nums2[temp.peek()]);
                        res[index] = nums2[i];
                    }
                    temp.pop();
                }
                temp.add(i);
            }
        }

        return res;
    }
}

你可能感兴趣的:(leetcode,代码随想录,算法,算法)