C#LeetCode刷题之#475-供暖器(Heaters)

C#LeetCode刷题之#475-供暖器(Heaters)

问题

冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。

现在,给出位于一条水平线上的房屋和供暖器的位置,找到可以覆盖所有房屋的最小加热半径。

所以,你的输入将会是房屋和供暖器的位置。你将输出供暖器的最小加热半径。

说明:

  • 给出的房屋和供暖器的数目是非负数且不会超过 25000。
  • 给出的房屋和供暖器的位置均是非负数且不会超过10^9。
  • 只要房屋位于供暖器的半径内(包括在边缘上),它就可以得到供暖。
  • 所有供暖器都遵循你的半径标准,加热的半径也一样。

输入: [1,2,3],[2]

输出: 1

解释: 仅在位置2上有一个供暖器。如果我们将加热半径设为1,那么所有房屋就都能得到供暖。

输入: [1,2,3,4],[1,4]

输出: 1

解释: 在位置1, 4上有两个供暖器。我们需要将加热半径设为1,这样所有房屋就都能得到供暖。

Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.

Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.

So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.

Note:

  • Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
  • Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
  • As long as a house is in the heaters’ warm radius range, it can be warmed.
  • All the heaters follow your radius standard and the warm radius will the same.

Input: [1,2,3],[2]

Output: 1

Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.

Input: [1,2,3,4],[1,4]

Output: 1

Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.

示例

public class Program {

    public static void Main(string[] args) {
        var S = "I speak Goat Latin";

        var res = ToGoatLatin(S);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static string ToGoatLatin(string S) {
        //按空格分隔
        var split = S.Split(' ');
        //定义结果
        var res = string.Empty;
        for(var i = 0; i < split.Length; i++) {
            if(IsStartsWithVowel(split[i])) {
                res += split[i];
            } else {
                //辅音字母开头时,首字母后置
                res += split[i].Substring(1) + split[i][0];
            }
            //追回字符串 ma 和按索引重复的字符 a
            res += "ma" + RepeatString(i + 1) + " ";
        }
        return res.Trim();
    }

    private static bool IsStartsWithVowel(string word) {
        //判断是不是元音字母
        var s = word[0].ToString().ToLower();
        return s == "a" || s == "e" || s == "i" || s == "o" || s == "u";
    }

    private static string RepeatString(int count) {
        //重复字符串
        var c = 'a';
        var res = string.Empty;
        for(var i = 0; i < count; i++) {
            res += c;
        }
        return res;
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

Imaa peaksmaaa oatGmaaaa atinLmaaaaa

分析:

显而易见,以上算法的时间复杂度为: O(n)​ 。

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。

转载请注明本文地址:https://www.byteflying.com/archives/3997

发表评论

登录后才能评论