leetcode475

时间:2023-03-09 17:12:17
leetcode475
public class Solution {
public int FindRadius(int[] houses, int[] heaters) {
houses = houses.Distinct().ToArray();//去重
heaters = heaters.Distinct().ToArray();//去重 var temphouses = houses.Except(houses.Intersect(heaters)).ToArray();
//var tempheaters = heaters.Except(heaters.Intersect(houses)).ToArray(); houses = temphouses;
//heaters = tempheaters; if (houses.Length == )
{
return ;
} //将房间与炉子合并到一个列表中
var list = new List<KeyValuePair<int, int>>();//key是坐标,value=0表示房间,value=1表示火炉
foreach (var house in houses)
{
list.Add(new KeyValuePair<int, int>(house, ));
}
foreach (var heater in heaters)
{
list.Add(new KeyValuePair<int, int>(heater, ));
} list = list.OrderBy(x => x.Key).ToList();//根据坐标排序 var min = int.MinValue; var minList = new List<int>(); //根据每个房间,找其最近的炉子
for (int i = ; i < list.Count; i++)
{
if (list[i].Value == )
{
var house = list[i].Key;//找到一所房间的坐标 var j1 = i - ;//循环,找前面的第一个炉子
var dis1 = int.MaxValue;
while (j1 >= )
{
if (list[j1].Value == )
{
dis1 = Math.Abs(house - list[j1].Key);
break;
}
j1--;
} var j2 = i + ;//循环,找后面的第一个炉子
var dis2 = int.MaxValue;
while (j2 < list.Count)
{
if (list[j2].Value == )
{
dis2 = Math.Abs(house - list[j2].Key);
break;
}
j2++;
} var dis = Math.Min(dis1, dis2);//距离当前房间,最近的炉子的距离
minList.Add(dis);
}
} min = minList.Max(); return min;
}
}

https://leetcode.com/problems/heaters/#/description