栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【算法刷题日志】(第一天)——数组

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【算法刷题日志】(第一天)——数组

【算法刷题日志】(第一天)——数组

✨如果喜欢的话,欢迎大家关注,点赞,评论,收藏!
本人博客的首页:crisp制药
本人是一个JAVA初学者,分享一下自己的所学,如果有错误,希望大家能告知,谢谢!


文章目录
    • 增量元素之间的最大差值
      • 解题思路:
    • 商品折扣后的最终价格
      • 题解思路:
    • 多个数组求交集
      • 题解思路:
    • 找到最接近 0 的数字
      • 题解思路
    • 总结

增量元素之间的最大差值

链接:题目链接

解题思路:

根据题意可以枚举数组中的每个数,求出最小值,然后每次枚举判断来更新两数的差值,从而求出最大的差值。

class Solution {
    public int maximumDifference(int[] nums) {
        int n = nums.length, ans = -1;
        for (int i = 0, min = nums[0]; i < n; i++) {
            if (nums[i] > min) ans = Math.max(ans, nums[i] - min);
            min = Math.min(min, nums[i]);
        }
        return ans;
    }
}
商品折扣后的最终价格

题目链接

题解思路:

这个题其实就是找某个元素在右边第一个比其更小的元素是哪个。所以用单调栈就可以o(n)的时间复杂度解决这个问题

class Solution {
    public int[] finalPrices(int[] prices) {
         Stackstack=new Stack<>(); //单调栈
        int[]res=new int[prices.length];
        for (int i = 0; i 
        //java里Stack的peek方法是返回栈顶的元素但不移除它,pop则是返回且移除它
            while (!stack.isEmpty()&&prices[stack.peek()]>=prices[i]){
                int index=stack.pop();
                res[index]=prices[index]-prices[i];
            }
            stack.push(i);
        }
        while (!stack.isEmpty()){
            int index=stack.pop();
            res[index]=prices[index];
        }
        return res;
    }
}
多个数组求交集

题目链接

题解思路:

因此我们自行创建一个数组存储保存该数字出现的次数。由于每组数据中不包含重复元素,则如果一个元素出现的次数等于nums.length则这个数字在该每一组数据中都出现,ilst默认升序排序

class Solution {
int[] temp = new int[1001];
    public List intersection(int[][] nums)//创建一个方法名,返回的类型为集合 {
      int n = nums.length;
      List ans = new ArrayList();
        for(int i = 0;i
            for(int j = 0;j
                ++temp[nums[i][j]];//遍历进行计数
            }
        }
        for(int i =1;i<1001;++i){
            if(temp[i]==n){//判断是否每个数组都出现过
                ans.add(i);
            }
        }
        return ans;
    }



}
找到最接近 0 的数字

题解思路

这题就是简单的模拟~,遍历寻找最大值
Integer.MAX_VALUE表示int数据类型的最大取值数:2 147 483 647
Integer.MIN_VALUE表示int数据类型的最小取值数:-2 147 483 648
Math.abs()代表的是取绝对值的意思

class Solution {
    public int findClosestNumber(int[] nums) {
        int ans = Integer.MAX_VALUE;
        for(int num : nums) {
            int absNum = Math.abs(num);
            if(absNum < Math.abs(ans) || (absNum == Math.abs(ans) && num > ans)) {
                ans = num;
            }
        }
        return ans;
    }
}
总结

这就是四道很基础的与数组有关的算法题,觉得写的还不错的朋友可以三连支持一下哦~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/862079.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号