1. 程式人生 > >力扣演算法題簡單(一)

力扣演算法題簡單(一)

    1. 環形連結串列
    public bool HasCycle(ListNode head)
    {
        if (head == null) return false;

        HashSet<ListNode> bill = new HashSet<ListNode>();

        while (head != null)
        {
            if (bill.Contains(head))
            {
                return
true; } else { bill.Add(head); } head = head.next; } return false; }
    1. 刪除排序陣列中的重複項
    public int RemoveDuplicates(int[] nums)
    {
        if (nums.Length == 0) return 0;
        int
i = 0; for (int j = 1; j < nums.Length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return i + 1; }
    1. 合併兩個有序連結串列
    public ListNode MergeTwoLists(ListNode
l1, ListNode l2) { ListNode head = new ListNode(0); ListNode cur = head; while (l1 != null && l2 != null) { if (l1.val < l2.val) { cur.next = l1; cur = l1; l1 = l1.next; } else { cur.next = l2; cur = l2; l2 = l2.next; } } if (l1 == null) { cur.next = l2; } if (l2 == null) { cur.next = l1; } return head.next; }
    1. 最大子序和
    public int MaxSubArray(int[] nums)
    {
        if (nums.Length == 0) return 0;
        int result = nums[0];
        int current = nums[0];
        for (int i = 1; i < nums.Length; i++)
        {
            if (current < 0) current = nums[i];
            else current += nums[i];
            if (current >= result)
            {
                result = current;
            }
        }
        return result;
    }
    1. 有效的括號
    public bool IsValid(string s)
    {
        if (string.IsNullOrEmpty(s)) return true;
        Dictionary<char, char> dict = new Dictionary<char, char>();
        dict.Add(')', '(');
        dict.Add(']', '[');
        dict.Add('}', '{');
        Stack<char> stack = new Stack<char>();
        for (int i = 0; i < s.Length; i++)
        {
            if (stack.Count == 0)
            {
                stack.Push(s[i]);
                continue;
            }
            char temp;
            dict.TryGetValue(s[i], out temp);
            if (stack.Peek() == temp) stack.Pop();
            else
                stack.Push(s[i]);
        }

        if (stack.Count == 0) return true;
        else
            return false;
    }
    1. 相交連結串列
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        /**
        定義兩個指標, 第一輪讓兩個到達末尾的節點指向另一個連結串列的頭部, 最後如果相遇則為交點(在第一輪移動中恰好抹除了長度差)
        兩個指標等於移動了相同的距離, 有交點就返回, 無交點就是各走了兩條指標的長度
        **/
        if(headA == null || headB == null) return null;
        ListNode pA = headA, pB = headB;
        // 在這裡第一輪體現在pA和pB第一次到達尾部會移向另一連結串列的表頭, 而第二輪體現在如果pA或pB相交就返回交點, 不相交最後就是null==null
        while(pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }
}