1.leetCode_350题
给定两个数组,编写一个函数来计算它们的交集。
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[4,9]
我自己想的是先把两个数组排序,然后循环遍历两个数组
package leetCode_350;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Program: Created with IntelliJ IDEA
* Description:给定两个数组,编写一个函数来计算它们的交集。
* <p>
* Author: Nin9Wan9
* Time:2021-10-13 10:42
**/
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
//拿一个顺序表来接受交集的数组
List<Integer> list = new ArrayList<>();
//将两个数组进行排序
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
//遍历两个数组
while(i < nums1.length && j < nums2.length){
if (nums1[i] == nums2[j]){
list.add(nums1[i]);
i++;
j++;
}else if(nums1[i] > nums2[j]){
j++;
}else{
i++;
}
}
//将list中的元素添加到数组中
int[] res = new int[list.size()];
for (int l = 0; l < list.size(); l++){
res[l] = list.get(l);
}
return res;
}
}
public class Solution{
//哈希表来解
public int[] intersect(int[] nums1, int[] nums2){
//将长度较小的数组的元素和它的个数添加到哈希表中
HashMap<Integer,Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
//先把数组nums1中的元素存放到map中,其中key存放数组中的元素,value存放该元素出现在数组中的次数
for (int i = 0; i < nums1.length; i++){
map.put(nums1[i],map.getOrDefault(nums1[i],0)+1);
}
//然后在遍历nums2数组,查看map中是否包含num2的元素,如果包含,加吧当前值加入到list中,然后再把对应的value值减1
for (int i = 0; i < nums2.length; i++){
if (map.getOrDefault(nums2[i],0) > 0){
list.add(nums2[i]);
map.put(nums2[i],map.getOrDefault(nums2[i],0)-1);
}
}
int[] res = new int[list.size()];
for (int l = 0; l < list.size(); l++){
res[l] = list.get(l);
}
return res;
}
}
2. leetCode.121买卖股票的最大值
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
示例 1:输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
示例 2:输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 没有交易完成, 所以最大利润为 0。
这道题刚拿到没有想法,看了题解,贪心算法求解,能看懂。
public class Solution {
public int maxProfit(int[] price) {
//贪心算法
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int i = 0; i < price.length; i++) {
if (price[i] < minPrice) {
minPrice = price[i];
} else if (price[i] - minPrice > maxProfit) {
maxProfit = price[i] - minPrice;
}
}
return maxProfit;
}
}