[力扣] 算法 1~3 (C#)

1. 两数之和

using index = System.Int32;
public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        var map = new Dictionary<int, index>();
        for (var i = 0; i < nums.Length; i++)
        {
            if (map.TryGetValue(target - nums[i], out var index))
                return new int[] { i, index };
            map[nums[i]] = i;
        }
        throw new Exception();
    }
}

2. 两数相加

public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
    {
        var head = new ListNode(-1);
        var curr = head;
        var carry = 0;
        while (l1 != null || l2 != null)
        {
            curr = curr.next = new ListNode(carry + (l1?.val ?? 0) + (l2?.val ?? 0));
            carry = curr.val / 10;
            curr.val %= 10;
            l1 = l1?.next;
            l2 = l2?.next;
        }
        if (carry != 0) curr.next = new ListNode(carry);
        return head.next;
    }
}

3. 无重复字符的最长子串

using index = System.Int32;
public class Solution {
    public int LengthOfLongestSubstring(string s)
    {
        var map = new Dictionary<char, index>();// 也可以用HashSet
        int ret = 0, cnt = 0;
        for (var i = 0; i < s.Length; i++, cnt++)
        {
            if (map.TryGetValue(s[i], out var index))
            {
                if (cnt > ret) ret = cnt;
                for (var j = i - cnt; j <= index; j++, cnt--)
                    map.Remove(s[j]);
            }
            map[s[i]] = i;
        }
        return Math.Max(ret, cnt);
    }
}

发表评论