Leetcode刷题 2021.02.23
Leetcode1726 同积元组
给你一个由 不同 正整数组成的数组 nums ,请你返回满足 a * b = c * d 的元组 (a, b, c, d) 的数量。其中 a、b、c 和 d 都是 nums 中的元素,且 a != b != c != d 。
这类求相等和,相等积的对数的题。给的数据规模又不大的题,一定就是O(n^2),用map记录啦。因为要求四个位数都不相等,所以可以根据情况剪枝。
class Solution {
public int tupleSameProduct(int[] nums) {
int n = nums.length, res = 0;
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
//如果和上个数相等就不要做了
if (nums[j] == nums[i]) continue;
//查看是否有相等的积,并且每一对都能形成8个答案,所以最后答案一定是8的倍数了
int temp = nums[i] * nums[j];
if (map.containsKey(temp)){
res += 8 * map.get(temp);
}
//放到mao中
map.put(temp, map.getOrDefault(temp, 0) + 1);
}
}
return res;
}
}
Leetcode334 递增的三元子序列
给你一个整数数组 nums ,判断这个数组中是否存在长度为 3 的递增子序列。
如果存在这样的三元组下标 (i, j, k) 且满足 i < j < k ,使得 nums[i] < nums[j] < nums[k] ,返回 true ;否则,返回 false 。
这题一开始的想法就是单调栈,但是想不到O(1)的解法,看了题解觉得很简单又很巧妙。有一些奇淫巧计真的是学不来啊。
class Solution {
public boolean increasingTriplet(int[] nums) {
int n = nums.length;
if (n < 3) return false;
int min = Integer.MAX_VALUE;
int sec = Integer.MAX_VALUE;
//遍历的过程中维护最小值和次小值就行
for(int num : nums){
//如果小于最小值,说明一定不能形成子序列,更新一下
if (num <= min){
min = num;
//同理
}else if (num <= sec){
sec = num;
//否则就是大于最小值,又大于次小值,那么就返回true了
//那么会不会出现最小值在次小值后面呢?
//不会,因为是先更新的最小值
}else{
return true;
}
}
return false;
}
}
Leetcode1328 破坏回文串
给你一个回文字符串 palindrome ,请你将其中 一个 字符用任意小写英文字母替换,使得结果字符串的字典序最小,且 不是 回文串。
请你返回结果字符串。如果无法做到,则返回一个空串。
这题感觉还是比较简单的,因为要字典序最小又要破坏回文串。那么把不是’a’变成’a’就行了。
还有一种情况就是全’a’的情况,那把最后一位变成’b’就行
class Solution {
public String breakPalindrome(String palindrome) {
int n = palindrome.length();
if (n == 1) return "";
for(int i = 0; i < n / 2; i++){
//用charAt时间比较慢,但是代码比较少
if (palindrome.charAt(i) != 'a'){
return palindrome.substring(0, i) + 'a' + palindrome.substring(i + 1);
}
}
return palindrome.substring(0, n - 1) + 'b';
}
}