力扣算法题简单(二)

    1. 链表的中间结点
    public ListNode MiddleNode(ListNode head)
    {
        ListNode slow = head, fast = head;
        //快慢指针法
        while (fast != null && fast.next != null)
        {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    1. 找不同
    public char FindTheDifference(string s, string t)
    {
        var cs = s.ToCharArray();
        Array.Sort(cs);
        var ct = t.ToCharArray();
        Array.Sort(ct);
        int i = 0;
        for (; i < cs.Length; i++)
        {
            if (cs[i] != ct[i])
            {
                return ct[i];
            }
        }
        return ct[i];
    }
  1. 队列实现栈
public class MyStack
{
    Queue<int> queue;
    /** Initialize your data structure here. */
    public MyStack()
    {
        queue = new Queue<int>();
    }

    /** Push element x onto stack. */
    public void Push(int x)
    {
        var temp = new Queue<int>();

        temp.Enqueue(x);
        var items = queue.ToList();
        foreach (var item in items)
        {
            temp.Enqueue(item);
        }

        queue = temp;
    }

    /** Removes the element on top of the stack and returns that element. */
    public int Pop()
    {
        if (!Empty())
        {
            return queue.Dequeue();
        }
        else
        {
            return -1;
        }
    }

    /** Get the top element. */
    public int Top()
    {
        if (!Empty())
        {
            var bill = queue.ToList();
            return bill[0];
        }
        else
        {
            return -1;
        }

    }

    /** Returns whether the stack is empty. */
    public bool Empty()
    {
        return queue.Count == 0;
    }
}
    1. 两句话中的不常见单词
    public string[] UncommonFromSentences(string A, string B)
    {
        var stringSum = $"{A} {B}";
        List<string> list = stringSum.Split(' ').ToList();

        Dictionary<string, int> dict = new Dictionary<string, int>();
        foreach (string item in list)
        {
            if (!dict.ContainsKey(item))
            {
                dict.Add(item, 1);
            }
            else
            {
                dict[item]++;
            }
        }

        return dict.Where(n => n.Value == 1).Select(w => w.Key).ToArray();
    }
    1. 最大连续1的个数
  public int FindMaxConsecutiveOnes(int[] nums)
    {
        int result = 0, temp = 0;
        for (int i = 0; i < nums.Length; i++)
        {
            if (nums[i] == 1)
            {
                temp++;
            }
            else
            {
                temp = 0;
            }
            if (temp > result)
            {
                result = temp;
            }
        }
        return result;
    }
    1. 删列造序
public static class CharAtExtention
{
    public static char CharAt(this string s, int index)
    {
        if ((index >= s.Length) || (index < 0))
            return ' ';
        return s.Substring(index, 1).ToCharArray()[0];
    }
}

public class AboutLeetcode : MonoBehaviour
{

    private void Start()
    {

    }

    public int MinDeletionSize(string[] A)
    {
        if (A.Length == 0)
        {
            return 0;
        }
        int count = 0;
        for (int j = 0, len = A[0].Length; j < len; j++)
        {
            for (int i = 1; i < A.Length; i++)
            {
                if (A[i].CharAt(j) < A[i - 1].CharAt(j))
                {
                    count++;
                    break;
                }
            }
        }
        return count;
    }
}
    1. 数字的补数
    public int FindComplement(int num)
    {
        string str = Convert.ToString(num, 2);

        if (num == 0 || num == 1)
        {
            return 0;
        }

        StringBuilder strb = new StringBuilder();
        for (int i = 0; i < str.Length; i++)
        {
            if (str[i] == '0')
            {
                strb.Append('1');
            }
            else
            {
                strb.Append('0');
            }
        }

        return Convert.ToInt32(strb.ToString(), 2);
    }
    1. 翻转二叉树
    public TreeNode InvertTree(TreeNode root)
    {
        if (root == null) return null;
        var wap = root.left;
        root.left = root.right;
        root.right = wap;
        InvertTree(root.left);
        InvertTree(root.right);
        return root;
    }
    1. 自除数
    private bool isDividing(int num)
    {
        int temp = num;
        while (temp != 0)
        {
            if (temp % 10 == 0) return false;
            if (num % (temp % 10) != 0) return false;
            else
                temp /= 10;
        }
        return true;
    }

    public IList<int> SelfDividingNumbers(int left, int right)
    {
        List<int> list = new List<int>();
        for (int i = left; i <= right; i++)
        {
            if (isDividing(i) == true) list.Add(i);
        }
        return list;
    }
    1. N叉树的前序遍历
        var list = new List<int>();
        if (root == null) return list;
        var stack = new Stack<Node>();
        stack.Push(root);

        //确定序列中的任何元素是否存在或满足条件。
        while (stack.Any())
        {
            var pop = stack.Pop();
            list.Add(pop.val);
            if (pop.children != null)
            {
                for (var i = pop.children.Count() - 1; i >= 0; i--)
                    stack.Push(pop.children[i]);
            }
        }
        return list;
    1. N叉树的后序遍历
    public IList<int> Postorder(Node root)
    {
        if (root == null) return new List<int>();
        var list = new List<int>();

        if (root.children != null)
        {
            foreach (var child in root.children)
            {
                list.AddRange(Postorder(child));
            }
        }
        list.Add(root.val);
        return list;
    }
    1. 单值二叉树
    public bool IsUnivalTree(TreeNode root)
    {

        List<int> list = Bianli(root);
        int k = 0;
        if (list.Count > 0)
        {
            k = list[0];
        }
        return list.All(n => n == k);

    }

    public List<int> Bianli(TreeNode root)
    {
        List<int> list = new List<int>();

        if (root != null)
        {
            list.Add(root.val);
        }
        else
        {
            return list;
        }

        list.AddRange(Bianli(root.left));
        list.AddRange(Bianli(root.right));

        return list;
    }
  1. N叉树的最大深度
    public int MaxDepth(Node root)
    {
        if (root == null) return 0;
        var res = 0;
        if (root.children != null && root.children.Count != 0)
        {
            foreach (var child in root.children)
            {
                var depth = MaxDepth(child);
                res = Math.Max(res, depth);
            }
        }

        return res + 1;
    }
    1. 最近的请求次数
	public class RecentCounter {
        private Queue<int> _queue = null;
        public RecentCounter()
        {
            _queue = new Queue<int>();
        }

        public int Ping(int t)
        {
            _queue.Enqueue(t);
            while(t-_queue.Peek()>3000)
            {
                _queue.Dequeue();
            }
            return _queue.Count;
        }
	}
    1. Excel表列序号
    public int TitleToNumber(string s)
    {
        /*方法一
        int n = s.Length;
        int res = 0;
        int temp = 1;
        for(int i = n; i >= 1; i--)
        {
            res += (s[i - 1] - 'A' + 1) * temp;
            temp *= 26;
        }
        return res;
        */
        int i = s.Length - 1;
        return s.ToCharArray().Select(x => x - 'A' + 1).Select(x => (int)(x * Math.Pow(26, i--))).Sum();
    }
    1. 最小差值 I
    public int SmallestRangeI(int[] A, int K)
    {
        Array.Sort(A);
        int sum = (A[A.Length - 1] - A[0] - (2 * K));
        if (sum <= 0) return 0;
        else
            return sum;
    }
    1. 转置矩阵
    public int[][] Transpose(int[][] A)
    {
        var m = A.Length;
        var n = A[0].Length;
        var result = new int[n][];

        for (int i = 0; i < n; i++)
        {
            result[i] = new int[m];
        }

        for (var i = 0; i < n; i++)
        {
            for (var j = 0; j < m; j++)
            {
                result[i][j] = A[j][i];
            }
        }
        return result;
    }

    1. 子域名访问计数
    public IList<string> SubdomainVisits(string[] cpdomains)
    {
        Dictionary<string, int> dict = new Dictionary<string, int>();

        foreach (var item in cpdomains)
        {
            string[] sArray = item.Split(' ');
            string ss = sArray[1];
            int count = Convert.ToInt32(sArray[0]);

            if (!dict.ContainsKey(ss))
            {
                dict.Add(ss, count);
            }
            else
            {
                dict[ss] += count;
            }

            while (ss.IndexOf('.') != -1)
            {
                string temp = ss.Substring(ss.IndexOf('.') + 1);

                if (!dict.ContainsKey(temp))
                {
                    dict.Add(temp, count);
                }
                else
                {
                    dict[temp] += count;
                }

                ss = temp;
            }
        }

        return dict.Select(n => n.Value.ToString() + " " + n.Key).ToList();
    }
    1. 交替位二进制数
    public bool HasAlternatingBits(int n)
    {
        //&全一才一,| 有一就一,箭头方向指向移动方向,右边值移动多少位
        int temp = n ^ (n >> 1);
        return (temp & (temp + 1)) == 0;
    }
    1. 将有序数组转换为二叉搜索树
    public TreeNode sortedArrayToBST(int[] nums)
    {
        // 左右等分建立左右子树,中间节点作为子树根节点,递归该过程
        if (nums == null || nums.Length == 0)
        {
            return null;
        }
        return buildTree(nums, 0, nums.Length - 1);
    }

    private TreeNode buildTree(int[] nums, int l, int r)
    {
        if (l > r)
        {
            return null;
        }
        if (l == r)
        {
            return new TreeNode(nums[l]);
        }
        int mid = (l + r) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = buildTree(nums, l, mid - 1);
        root.right = buildTree(nums, mid + 1, r);
        return root;
    }

猜你喜欢

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