总结:这周周赛较难,勉强做两道的水准,但是非常有意思。
1128. Number of Equivalent Domino Pairs
这个问题我先用暴力解法,显然按照数据范围复杂度10^8过不了,然后就先统一骨牌形式(小,大),再排序,然后扫一遍计算:这个算法时间复杂度nlogn,不是很优雅,容易出错。
class Solution {
public int numEquivDominoPairs(int[][] d) {
int ans=0,tmp=0;
for(int i=0;i<d.length;i++){
if(d[i][0]>d[i][1]){
tmp=d[i][0];
d[i][0]=d[i][1];
d[i][1]=tmp;
}
}
Arrays.sort(d,(a,b)->a[0]-b[0]==0?a[1]-b[1]:a[0]-b[0]);
for(int i=0,j=0;i+1<d.length;i++){
j=i;
while(j+1<d.length && d[j][0]==d[j+1][0] && d[j][1]==d[j+1][1])
j++;
if(j>i)
ans+=(j-i+1)*(j-i)/2;
i=j;
}
return ans;
}
}
follow-up
注意到骨牌的范围1-9,可以使用十进制整数编码的思想,性能提高不少。
class Solution {
public int numEquivDominoPairs(int[][] d) {
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<d.length;i++){
int val=0;
if(d[i][0]<d[i][1])
{
val=d[i][0]*10+d[i][1];
}
else
{
val=d[i][1]*10+d[i][0];
}
map.put(val,map.getOrDefault(val,0)+1);
}
int ans=0;
for(int i:map.keySet()){
int count=map.get(i);
ans+=count*(count-1)/2;
}
return ans;
}
}
1129. Shortest Path with Alternating Colors
这个问题显然是BFS,但是状态比原来多了一个维度,边的颜色也是一个需要考虑的状态。首先对图构建邻接表,既可以用二维矩阵,也可以用HashMap<Integer,List>,或者线性表数组。
算法一:对于非0的目标点,可能存在有两种方式可以到达,分开考虑即可。邻接矩阵多出一个颜色维度。Triple类存储的是当前到达的点编号node、从当前点出发路径的颜色color,到达当前点所用的距离dist。在两种方式的BFS中,需要判重,因为从相同起点出发走相同颜色路线这个状态转换是重复的,这里将“点编号_颜色”作为字符串进行判重。
class Solution {
class Triple{
int node;
int color;
int dist;
public Triple(int node,int color,int dist)
{
this.node=node;
this.color=color;
this.dist=dist;
}
}
public int[] shortestAlternatingPaths(int n, int[][] red_edges, int[][] blue_edges) {
int [][][] adj=new int[2][n][n];
int[] ans=new int[n];
Arrays.fill(ans,Integer.MAX_VALUE);
ans[0]=0;
for(int i=0;i<red_edges.length;i++)
adj[0][red_edges[i][0]][red_edges[i][1]]=1;
for(int i=0;i<blue_edges.length;i++){
adj[1][blue_edges[i][0]][blue_edges[i][1]]=1;
}
bfs(0,adj,ans);
bfs(1,adj,ans);
for(int i=0;i<n;i++)
{
if(ans[i]==Integer.MAX_VALUE)
ans[i]=-1;
}
return ans;
}
public void bfs(int color,int[][][] adj,int[] ans){
Queue<Triple> q=new LinkedList<>();
q.add(new Triple(0,color,0));
HashSet<String> set=new HashSet<>();
set.add("0_"+color);
while(!q.isEmpty()){
Triple tmp=q.poll();
ans[tmp.node]=Math.min(ans[tmp.node],tmp.dist);
int curColor=1-tmp.color;
for(int i=0;i<ans.length;i++){
if(adj[curColor][tmp.node][i]==1){
String code=i+"_"+curColor;
if(!set.contains(code)){
q.add(new Triple(i,curColor,tmp.dist+1));
set.add(code);
}
}
}
}
}
}
算法二:
统一考虑两种方案,但是存储两种方案的最短距离
class Solution {
class Pair{ //状态结构,某条路径的起点和颜色
int color;
int from;
public Pair(int color,int from){
this.color=color;
this.from=from;
}
}
public int[] shortestAlternatingPaths(int n, int[][] red_edges, int[][] blue_edges) {
HashMap<Integer,List<Integer>> redMap=new HashMap<>();
HashMap<Integer,List<Integer>> blueMap=new HashMap<>();
int[][] steps=new int[2][n];
int[] ans=new int[n];
Arrays.fill(steps[0],1,n,Integer.MAX_VALUE);
Arrays.fill(steps[1],1,n,Integer.MAX_VALUE);
for(int i=0;i<red_edges.length;i++)
redMap.computeIfAbsent(red_edges[i][0],k->new ArrayList<>()).add(red_edges[i][1]);
for(int i=0;i<blue_edges.length;i++)
blueMap.computeIfAbsent(blue_edges[i][0],k->new ArrayList<>()).add(blue_edges[i][1]);
Queue<Pair> q=new LinkedList<>();
q.add(new Pair(0,0));
q.add(new Pair(1,0));
while(!q.isEmpty()){
Pair tmp=q.poll();
Map<Integer,List<Integer>> map=(tmp.color==0?redMap:blueMap);
if(!map.containsKey(tmp.from))
continue;
for(int i:map.get(tmp.from)){
if(steps[1-tmp.color][i]==Integer.MAX_VALUE){
steps[1-tmp.color][i]=steps[tmp.color][tmp.from]+1;
q.add(new Pair(1-tmp.color,i));
}
}
}
for(int i=1;i<n;i++)
{
int minDist=Math.min(steps[0][i],steps[1][i]);
if(minDist==Integer.MAX_VALUE)
ans[i]=-1;
else
ans[i]=minDist;
}
return ans;
}
}
1130. Minimum Cost Tree From Leaf Values
算法一:Divide and Conquer,将当前数组划分为左右两个子数组,求子问题的最优解。算法复杂度O(n^3)
class Solution {
public int mctFromLeafValues(int[] arr) {
int n=arr.length;
int[][] max=new int[n][n];
int[][] sum=new int[n][n];
for(int len=1;len<=n;len++)
{
for(int start=0;start+len-1<n;start++)
{
int end=start+len-1;
if(start==end)
{
max[start][end]=arr[start];
sum[start][end]=0;
}
else
{
max[start][end]=Math.max(max[start][end-1],arr[end]);
int curSum=Integer.MAX_VALUE;
for(int i=start;i<end;i++){
curSum=Math.min(curSum,sum[start][i]+sum[i+1][end]+max[start][i]*max[i+1][end]);
}
sum[start][end]=curSum;
}
}
}
return sum[0][n-1];
}
}
算法二:归并排序
class Solution {
int res = 0;
public int mctFromLeafValues(int[] arr)
{
mergesort(arr, 0, arr.length - 1);
return res;
}
private void mergesort(int[] arr, int low, int high)
{
if (low >= high) return;
int maxIndex = low, maxNum = Integer.MIN_VALUE;
for (int i = low; i <= high; i++)
{
if (arr[i] > maxNum)
{
maxNum = arr[i];
maxIndex = i;
}
}
if (maxIndex == high) maxIndex--;
mergesort(arr, low, maxIndex);
mergesort(arr, maxIndex + 1, high);
int leftMax = maxIndex >= low ? arr[maxIndex] : 0;
int rightMax = maxIndex + 1 <= high ? arr[high]: 0;
res += leftMax * rightMax;
Arrays.sort(arr, low, high + 1);
}
}
class Solution {
public int mctFromLeafValues(int[] arr) {
int n=arr.length;
Stack<Integer> st=new Stack<>();
st.push(Integer.MAX_VALUE);
int ans=0;
for(int a:arr)
{
while(st.peek()<=a)
{
int tmp=st.pop();
ans+=tmp*Math.min(st.peek(), a);
}
st.push(a);
}
while(st.size()>2){
int tmp=st.pop();
ans+=tmp*st.peek();
}
return ans;
}
}
1131. Maximum of Absolute Value Expression
暴力法也能过,但是很丑。
利用绝对值性质打开绝对值确定曼哈顿距离的取值公式的各种情况。算法复杂度从O(N^2)下降到O(N)
class Solution {
public int maxAbsValExpr(int[] arr1, int[] arr2)
{
int[] arr=new int[arr1.length];
int[] a={-1,1},b={-1,1};
int ans=0;
for(int i:a)
{
for(int j:b)
{
for(int n=0;n<arr1.length;n++){
arr[n]=arr1[n]*i+arr2[n]*j+n;
}
int minVal=Integer.MAX_VALUE;
int maxVal=Integer.MIN_VALUE;
for(int n=0;n<arr1.length;n++){
minVal=Math.min(minVal,arr[n]);
maxVal=Math.max(maxVal,arr[n]);
}
ans=Math.max(ans,maxVal-minVal);
}
}
return ans;
}
}