题目1:1464. 数组中两元素的最大乘积
题解:可以直接排序一遍数组得到最大最小值,或者直接一次遍历得到第一第二大的值,注意点在于:每次数组值大于最大值之后,更新最大值之前还得把旧的最大值赋值给第二大。
class Solution {
public int maxProduct(int[] nums) {
int first = 1, second = 1;
for (int num : nums) {
if (num > first) {
second = first;
first = num;
} else if (num > second){
second = num;
}
}
return (first-1)*(second-1);
}
}
题目2:1636. 按照频率将数组升序排序
class Solution {
public int[] frequencySort(int[] nums) {
HashMap<Integer,Integer> map=new HashMap<>();
for(int num:nums){
map.put(num,map.getOrDefault(num,0)+1);
}
ArrayList<Map.Entry<Integer,Integer>> arrayList=new ArrayList<>(map.entrySet());
Collections.sort(arrayList,(o1,o2)-> o1.getValue().equals(o2.getValue()) ? (o2.getKey()-o1.getKey() ): (o1.getValue().compareTo(o2.getValue())));
int[] res=new int[nums.length];
int z=0;
for(int i=0;i<arrayList.size();i++){
for(int j=0;j<arrayList.get(i).getValue();j++){
res[z++]=arrayList.get(i).getKey();
}
}
return res;
}
}
题目3:1287. 有序数组中出现次数超过25%的元素
如果是以前,遇到这种题就直接上HashMap了。。现在根据题目必定有解,所以arr[i]==arr[i+len/4]就一定是唯一解,直接返回。
class Solution {
public int findSpecialInteger(int[] arr) {
int len = arr.length;
int t = len/4;
for(int i=0;i<t-t1;i++){
if(arr[i]==arr[i+t]){
return arr[i];
}
}
return -1;
}
}
题目4:436. 寻找右区间
依稀记得刚看过这题,果然是520那天的每日一题hh
class Solution {
public int[] findRightInterval(int[][] intervals) {
int n = intervals.length;
int[][] clone = new int[n][2];
for (int i = 0; i < n; i++) {
clone[i] = new int[]{intervals[i][0], i};
}
Arrays.sort(clone, (a,b)->a[0]-b[0]);
int[] ans = new int[n];
for (int i = 0; i < n;i++) {
int l = 0, r = n - 1;
while (l < r) {
int mid = l + r >> 1;
if (clone[mid][0] >= intervals[i][1]) {
r = mid;
} else {
l = mid + 1;
}
}
ans[i] = clone[r][0] >= intervals[i][1] ? clone[r][1] : -1;
}
return ans;
}
}