【算法刷题日志】(第一天)——数组
✨如果喜欢的话,欢迎大家关注,点赞,评论,收藏!😁
🌟本人博客的首页: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) {
Stack<Integer>stack=new Stack<>(); //单调栈
int[]res=new int[prices.length];
for (int i = 0; i <prices.length ; 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<Integer> intersection(int[][] nums)//创建一个方法名,返回的类型为集合 {
int n = nums.length;
List<Integer> ans = new ArrayList();
for(int i = 0;i<n;++i){
for(int j = 0;j<nums[i].length;++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;
}
}
💘总结这就是四道很基础的与数组有关的算法题,觉得写的还不错的朋友可以三连支持一下哦~
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)