力扣算法题简单(五)

    1. 二叉树的所有路径
    public IList<string> BinaryTreePaths(TreeNode root)
    {
        var res = new List<string>();
        if (root == null) return res;
        TreePaths(res, root, root.val + "");
        return res;
    }

    public static void TreePaths(IList<string> res, TreeNode root, string path)
    {
        if (root.left == null && root.right == null)
            res.Add(path);
        if (root.left != null)
            TreePaths(res, root.left, path + "->" + root.left.val);

        if (root.right != null)
        {
            TreePaths(res, root.right, path + "->" + root.right.val);
        }
    }
    1. 罗马数字转整数
    public int RomanToInt(string s)
    {
        Dictionary<char, int> dic = new Dictionary<char, int>()
        {
            ['I'] = 1,
            ['V'] = 5,
            ['X'] = 10,
            ['L'] = 50,
            ['C'] = 100,
            ['D'] = 500,
            ['M'] = 1000,
        };
        int res = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (i == s.Length - 1 || dic[s[i]] <= dic[s[i + 1]])
            {
                res += dic[s[i]];
            }
            else
            {
                res -= dic[s[i]];
            }
        }
        return res;
    }

    1. 叶子相似的树
 public bool LeafSimilar(TreeNode root1, TreeNode root2)
    {
        List<int> rootlist1 = GetXulie2(root1);
        List<int> rootlist2 = GetXulie2(root2);
        return rootlist1.SequenceEqual(rootlist2);
    }

    public List<int> GetXulie2(TreeNode root)
    {
        List<int> res = new List<int>();

        if (root == null) return res;

        if ((root.left == null) && (root.right == null))
        {
            res.Add(root.val);
        }

        res.AddRange(GetXulie2(root.left));
        res.AddRange(GetXulie2(root.right));

        return res;
    }
    1. 二进制间距
    public int BinaryGap(int N)
    {
        int[] A = new int[32];
        int t = 0;
        for (int i = 0; i < 32; ++i)
            if (((N >> i) & 1) != 0)
                A[t++] = i;

        int ans = 0;
        for (int i = 0; i < t - 1; ++i)
            ans = Math.Max(ans, A[i + 1] - A[i]);
        return ans;
    }
    1. 最大三角形面积
    public double LargestTriangleArea(int[][] points)
    {
        double area = 0d;
        for (int i = 0; i < points.Length; i++)
        {
            for (int j = i; j < points.Length - 1; j++)
            {
                for (int x = j; x < points.Length; x++)
                {
                    double x1 = points[i][0];
                    double y1 = points[i][1];
                    double x2 = points[j][0];
                    double y2 = points[j][1];
                    double x3 = points[x][0];
                    double y3 = points[x][1];

                    area = Math.Max(area, Math.Abs((x1 - x3) * (y2 - y3) - (x2 - x3) * (y1 - y3)));
                }
            }
        }

        return area / 2;
    }
    1. 设计哈希映射
public class MyHashMap {
    int[] map = new int[1000000];
    /** Initialize your data structure here. */
    public MyHashMap()
    {
        for(int i = 0; i < map.Length; i++)
        {
            map[i] = -1;
        }
    }

    /** value will always be non-negative. */
    public void Put(int key, int value)
    {
        map[key] = value;
    }

    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    public int Get(int key)
    {
        return map[key];
    }

    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    public void Remove(int key)
    {
        map[key] = -1;
    }
}
    1. 重新排列日志文件
    //判断是否是一个纯数字
    public bool IsNumeric(string str) //接收一个string类型的参数,保存到str里

    {
        if (str == null || str.Length == 0)    //验证这个参数是否为空
            return false;                           //是,就返回False
        ASCIIEncoding ascii = new ASCIIEncoding();//new ASCIIEncoding 的实例
        byte[] bytestr = ascii.GetBytes(str);         //把string类型的参数保存到数组里

        foreach (byte c in bytestr)                   //遍历这个数组里的内容
        {
            if (c < 48 || c > 57)                          //判断是否为数字
            {
                return false;                              //不是,就返回False
            }
        }
        return true;                                        //是,就返回True
    }

    public string[] ReorderLogFiles(string[] logs)
    {
        List<string> shuziList = new List<string>();
        List<string> zimuList = new List<string>();
        var c = from str in logs
                where IsNumeric(str.Split(' ')[1]) == true
                select str;
        shuziList.AddRange(c);

        var c2 = from str in logs
                 let jiujiu = str.Split(' ')
                 let cw = jiujiu[1]
                 where IsNumeric(cw) == false
                 select str;

        zimuList.AddRange(c2);
        zimuList.Sort((a, b) => a.Substring(a.IndexOf(" ") + 1).
            CompareTo(b.Substring(b.IndexOf(" ") + 1)));

        zimuList.AddRange(shuziList);
        return zimuList.ToArray();
    }
    1. 建立四叉树
 public Node construct(int[][] grid)
    {
        return fun(grid, 0, grid[0].Length, 0, grid.Length);
    }

    public Node fun(int[][] grid, int left, int right, int top, int bottom)
    {
        Node root = null;
        int key = grid[top][left];
        for (int i = top; i < bottom; i++)
        {
            for (int j = left; j < right; j++)
            {
                if (grid[i][j] != key)
                {
                    Node topLeft = fun(grid, left, (left + right) / 2, top, (top + bottom) / 2);
                    Node topRight = fun(grid, (left + right) / 2, right, top, (top + bottom) / 2);
                    Node bottomLeft = fun(grid, left, (left + right) / 2, (top + bottom) / 2, bottom);
                    Node bottomRight = fun(grid, (left + right) / 2, right, (top + bottom) / 2, bottom);
                    root = new Node(false, false, topLeft, topRight, bottomLeft, bottomRight);
                    return root;
                }
            }
        }
        root = new Node();
        root.val = key == 1 ? true : false;
        root.isLeaf = true;
        return root;
    }
    1. 山羊拉丁文
 public string ToGoatLatin(string S)
    {
        string[] ws = S.Split(' ');
        char[] yuanyin = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };

        for (int i = 0; i < ws.Length; i++)
        {
            bool isYuanKaitou = false;
            if (yuanyin.Contains(ws[i][0]))
            {
                isYuanKaitou = true;
            }
            else
            {
                isYuanKaitou = false;
            }

            if (isYuanKaitou)
            {
                ws[i] = ws[i] + "ma";
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j <= i; j++)
                {
                    sb.Append('a');
                }
                ws[i] += sb.ToString();
            }
            else
            {
                string kkk = Change(ws[i]);
                ws[i] = kkk + "ma";

                StringBuilder sb = new StringBuilder();
                for (int j = 0; j <= i; j++)
                {
                    sb.Append('a');
                }
                ws[i] += sb.ToString();
            }
        }
        return string.Join(" ", ws);
    }

    public string Change(string k)
    {
        StringBuilder sb = new StringBuilder(k);
        char c = sb[0];
        sb.Append(c);
        StringBuilder sb2 = new StringBuilder();
        for (int i = 1; i < sb.Length; i++)
        {
            sb2.Append(sb[i]);
        }
        return sb2.ToString();
    }
    1. 回旋镖的数量
public int NumberOfBoomerangs(int[,] points)
    {
        var res = 0;
        for(var i = 0; i < points.GetLength(0); ++i)
        {
            var dic = new Dictionary<double, int>();
            for(var j = 0; j < points.GetLength(0); ++j)
            {
                var a = points[i, 0] - points[j, 0];
                var b = points[i, 1] - points[j, 1];
                var c = a * a + b * b;
                if (dic.ContainsKey(c))
                {
                    dic[c]++;
                }else
                {
                    dic[c] = 1;
                }
            }

            foreach (var item in dic)
            {
                res += item.Value * (item.Value - 1);
            }
        }
        return res;
    }
    1. 验证外星语词典
   public int[] ordArray = new int[26];
    public bool IsAlienSorted(string[] words, string order)
    {
        for (int i = 0; i < 26; i++)
        {
            char alpha = order.ElementAt(i);
            ordArray[alpha - 97] = i;
        }

        for (int i = 1; i < words.Length; i++)
        {
            if (!IsOrder(words[i - 1], words[i])) return false;
        }
        return true;
        // dic = order.ToDictionary<char, int>(Sk);
        //string[] words2 = (string[])words.Clone();
        //int minLeng = words.Min(str => str.Length);
        //Sort(words2);
        //var temp = from str in words2
        //           orderby str.Sum(chaa => dic.Where(q => q.Value == chaa).Select(q => q.Key).ToArray()[0]) descending
        //           select str;
        //string[] words3 = temp.ToArray();

    }

    private bool IsOrder(string word1, string word2)
    {
        for (int i = 0; i < word1.Length && i < word2.Length; i++)
        {
            char ch1 = word1.ElementAt(i);
            char ch2 = word2.ElementAt(i);
            if (ordArray[ch1 - 97] > ordArray[ch2 - 97]) return false;

            else if (ordArray[ch1 - 97] < ordArray[ch2 - 97]) return true;
        }

        if (word1.Length > word2.Length) return false;
        return true;
    }
    1. 递增顺序查找树
public List<int> Go(TreeNode root)
    {
        List<int> list = new List<int>();
        if (root == null) return list;
        list.AddRange(Go(root?.left));
        list.Add(root.val);
        list.AddRange(Go(root?.right));
        return list;
    }


    public TreeNode IncreasingBST(TreeNode root)
    {
        if (root == null) return null;
        TreeNode sk;
        List<int> k = Go(root);

        sk = new TreeNode(k[0]);
        TreeNode bill = sk;
        k.RemoveAt(0);

        while (k.Count > 0)
        {
            int val = k[0];
            sk.right = new TreeNode(val);
            sk = sk.right;
            k.RemoveAt(0);
        }
        return bill;
    }
    1. 旋转数字
    public int RotatedDigits(int N)
    {
        int c = 0;
        String s;
        for (int i = 2; i <= N; i++)
        {
            s = i.ToString();
            if (s.IndexOf("3") != -1 || s.IndexOf("4") != -1 || s.IndexOf("7") != -1) { continue; }
            if (s.IndexOf("2") != -1 || s.IndexOf("5") != -1 || s.IndexOf("6") != -1 || s.IndexOf("9") != -1)
            {
                c++;
            }
        }
        return c;
    }
    1. 最短完整词
    public string ShortestCompletingWord(string licensePlate, string[] words)
    {
        string lp = licensePlate.ToLower();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lp.Length; i++)
        {
            if (lp[i] >= 'a' && lp[i] <= 'z')
            {
                sb.Append(lp[i]);
            }
        }
        string lp2 = sb.ToString();
        var c = from p in words
                where IsStr(lp2, p)
                orderby p.Length
                select p;
        var bb = c.ToArray();
        if (bb.Length != 0)
        {
            return c.ToArray()[0];
        }
        else
        {
            return null;
        }
    }

    //m是过滤了的
    public bool IsStr(string lp2, string o)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < o.Length; i++)
        {
            if (lp2.Contains(o[i]))
            {
                sb.Append(o[i]);
            }
        }
        string lp3 = sb.ToString();
        char[] a = lp2.ToArray();
        char[] b = lp3.ToArray();
        if (!a.Except(b).Any()&&IsEqulCount(a,b))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public bool IsEqulCount(char[] a, char[] b)
    {
        Dictionary<char, int> dic = new Dictionary<char, int>();
        for (int i = 0; i < a.Length; i++)
        {
            if (!dic.ContainsKey(a[i]))
            {
                dic.Add(a[i], 1);
            }
            else
            {
                dic[a[i]] += 1;
            }
        }
        Dictionary<char, int> dic2 = new Dictionary<char, int>();
        for (int i = 0; i < b.Length; i++)
        {
            if (!dic2.ContainsKey(b[i]))
            {
                dic2.Add(b[i], 1);
            }else
            {
                dic2[b[i]] += 1;
            }
        }
        Dictionary<char, int> dic3 = new Dictionary<char, int>();
        foreach (KeyValuePair<char,int> item in dic2)
        {
            if (dic.ContainsKey(item.Key))
            {
                dic3.Add(item.Key, item.Value);
            }
        }
        return dic3.All(keyandvalue => dic3[keyandvalue.Key] >= dic[keyandvalue.Key]);
    }
    1. 快乐数
    public bool IsHappy(int n) {
           //参考IsHappy2
        while(n != 1 && n != 4) {
            var sum = 0;
            while(n > 0) {
                sum += (n % 10) * (n % 10);
                n /= 10;
            }
            n = sum;
        }
        return n == 1;
    }
    1. 设计哈希集合
 public class MyHashSet
    {
        private List<int> data;
        /** Initialize your data structure here. */
        public MyHashSet()
        {
            data = new List<int>();
        }

        public void Add(int key)
        {
            if (!data.Contains(key))
            {
                data.Add(key);
            }
        }

        public void Remove(int key)
        {
            if (data.Contains(key))
            {
                data.Remove(key);
            }
        }

        /** Returns true if this set contains the specified element */
        public bool Contains(int key)
        {
            return data.Contains(key);
        }
    }
    1. 区域和检索 - 数组不可变
    public class NumArray
    {
        public int[] ks;
        public NumArray(int[] nums)
        {
            ks = nums;
        }

        public int SumRange(int i, int j)
        {

            int res = 0;

            for (int k = i; k <= j; k++)
            {
                res += ks[k];
            }

            return res;
        }
    }
    1. 检测大写字母
    public bool DetectCapitalUse(string word)
    {
        if (word.ToUpper().Equals(word)) return true;
        if (word.ToLower().Equals(word)) return true;
        if (word.ElementAt(0) >= 'a' && word.ElementAt(0) <= 'z') return false;

        for (int i = 1; i < word.Length; i++)
        {
            if (word.ElementAt(i) >= 'A' && word.ElementAt(i) <= 'Z') return false;
        }
        return true;
    }
    1. 把二叉搜索树转换为累加树
 public List<int> Go(TreeNode root)
    {
        List<int> list = new List<int>();
        if (root == null) return list;
        list.AddRange(Go(root?.left));
        list.Add(root.val);
        list.AddRange(Go(root?.right));
        return list;
    }

    public TreeNode ConvertBST(TreeNode root)
    {
        List<int> list = Go(root);
        Dictionary<int, int> dic = new Dictionary<int, int>();
        foreach (var item in list)
        {
            if (list.All(item2 => item >= item2))
            {
                dic.Add(item, item);
            }
            else
            {
                dic.Add(item, list.Where(it => it > item).Sum() + item);
            }
        }

        TreeNode root2 = root;
        if (root == null)
            return null;

        Queue<TreeNode> queue = new Queue<TreeNode>();
        queue.Enqueue(root);

        while (queue.Any())
        {
            var item = queue.Dequeue();
            item.val = dic[item.val];
            if (item.left != null)
            {
                queue.Enqueue(item.left);
            }

            if (item.right != null)
            {
                queue.Enqueue(item.right);
            }
        }

        return root2;
    }
    1. 十进制整数的反码
    public int BitwiseComplement(int N)
    {
        string k = Convert.ToString(N, 2);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < k.Length; i++)
        {
            if (k[i] == '0')
            {
                sb.Append('1');
            }
            else
            {
                sb.Append('0');
            }
        }
        return Convert.ToInt32(sb.ToString(), 2);
    }

猜你喜欢

转载自blog.csdn.net/qq_37811712/article/details/88539879