LCP 39. 无人机方阵
在 「力扣挑战赛」 开幕式的压轴节目 「无人机方阵」中,每一架无人机展示一种灯光颜色。 无人机方阵通过两种操作进行颜色图案变换:
调整无人机的位置布局
切换无人机展示的灯光颜色
给定两个大小均为 N*M 的二维数组 source 和 target 表示无人机方阵表演的两种颜色图案,由于无人机切换灯光颜色的耗能很大,请返回从 source 到 target 最少需要多少架无人机切换灯光颜色。
注意: 调整无人机的位置布局时无人机的位置可以随意变动。
示例 1:
输入:source = [[1,3],[5,4]], target = [[3,1],[6,5]]
输出:1
解释:
最佳方案为
将 [0,1] 处的无人机移动至 [0,0] 处;
将 [0,0] 处的无人机移动至 [0,1] 处;
将 [1,0] 处的无人机移动至 [1,1] 处;
将 [1,1] 处的无人机移动至 [1,0] 处,其灯光颜色切换为颜色编号为 6 的灯光;
因此从source 到 target 所需要的最少灯光切换次数为 1。
8819ccdd664e91c78cde3bba3c701986.gif
示例 2:
输入:source = [[1,2,3],[3,4,5]], target = [[1,3,5],[2,3,4]]
输出:0
解释:
仅需调整无人机的位置布局,便可完成图案切换。因此不需要无人机切换颜色
这题其实挺有难度的,解题代码如下:
void quick(int *a,int low,int high){
if(low<high){
int p=a[low],l=low,h=high;
while(low<high){
while(low<high&&a[high]>=p){
high--;
}
a[low]=a[high];
while(low<high&&a[low]<=p){
low++;
}
a[high]=a[low];
}
a[low]=p;
quick(a,l,low-1);
quick(a,low+1,h);
}
}
int minimumSwitchingTimes(int** source, int sourceSize, int* sourceColSize, int** target, int targetSize, int* targetColSize){
int n=sourceSize,m=sourceColSize[0];
int *a=(int *)malloc(sizeof(int)*m*n);
int *b=(int *)malloc(sizeof(int)*m*n);
int size=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
a[size]=source[i][j];
b[size++]=target[i][j];
}
}
quick(a,0,size-1);
quick(b,0,size-1);
int count=0;
int indexa=0;
int indexb=0;
while(indexa<size&&indexb<size){
// printf("%d %d |",a[indexa],b[indexb]);
if(a[indexa]==b[indexb]){
indexb++;
indexa++;
count++;
}
else if(a[indexa]>b[indexb]){
indexb++;
}
else{
indexa++;
}
}
// printf("%d ",count);
return size-count;
}