leetcode练习
350.两个数组的交集II
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> list1 = new ArrayList<>();
for (int num : nums1) {
list1.add(num);
}
List<Integer> list2 = new ArrayList<>();
for (int num : nums2) {
if (list1.contains(num)) {
list2.add(num);
// 从 list1 除去已匹配的数值
list1.remove(Integer.valueOf(num));
}
}
int[] array = list2.stream().mapToInt(Integer::intValue).toArray();
return array;
}
int[] array = list2.stream().mapToInt(Integer::intValue).toArray()将整型list转换为整型数组。
String[] strArray = list2.toArray(new String[list2.size()])将字符串list转换成字符串数组。
list.remove()删除符合标准的第一个元素,map.remove()删除key值符合的元素,但map.put(),key相同时覆盖之前value。
也可以通过遍历转化成数组
int[] res = new int[list2.size()];
int i = 0;
for (int num : list2) {
res[i++] = num;
}
也可以使用map实现
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer, Integer> map = new HashMap<>(nums1.length);
// 将 nums1 出现的数值及频次放入映射中
for (int num : nums1) {
Integer count = map.get(num);
if (count == null) {
map.put(num, 1);
} else {
map.put(num, ++count);
}
}
List<Integer> list = new ArrayList<>();
for (int num : nums2) {
// 获取映射中该数值出现的频次
Integer count = map.get(num);
if (count != null && count != 0) {
list.add(num);
// 注意每次匹配后,该数值的频次需要减 1(nums1 和 nums2 匹配的数值的频次要相同)
map.put(num, --count);
}
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
还可以使用双指针,先进行sort()排序,再进行比较。
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer> list = new ArrayList<>();
for (int i = 0, j = 0; i < nums1.length && j < nums2.length; ) {
if (nums1[i] < nums2[j]) {
i++;
} else if (nums1[i] > nums2[j]) {
j++;
} else {
list.add(nums1[i]);
i++;
j++;
}
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
121.买卖股票的最佳时间
这是一道动态规划题,推导公式:前i天的最大收益 = max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格}
public int maxProfit(int[] prices) {
int maxPro = 0, minPrice = Integer.MAX_VALUE;
for (int price : prices) {
minPrice = Math.min(minPrice, price);
maxPro = Math.max(maxPro, price - minPrice);
}
return maxPro;
}