LeetCode50题-Day4-16/20/21

本文详细介绍了LeetCode中三道经典算法题目的解决方案,包括16题(三数之和)的暴力求解与排序优化方法,20题(有效括号)的栈应用,以及21题(合并两个有序列表)的链表合并技巧。通过C#和Python两种语言展示了高效实现。
摘要由CSDN通过智能技术生成

LeetCode50题(17天)-Day4

16 最接近的三数之和

  • 题号:16
  • 难度:中等
  • https://leetcode-cn.com/problems/3sum-closest/

给定一个包括n个整数的数组nums和一个目标值target。找出nums中的三个整数,使得它们的和与target最接近。返回这三个数的和。假定每组输入只存在唯一答案。

示例 :

例如,给定数组 nums = [-121-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

实现

第一种:利用暴力算法

  • 状态:通过
  • 125 / 125 个通过测试用例
  • 执行用时: 680 ms, 在所有 C# 提交中击败了 12.07% 的用户
  • 内存消耗: 23.7 MB, 在所有 C# 提交中击败了 7.41% 的用户
public class Solution 
{
    public int ThreeSumClosest(int[] nums, int target) 
    {
        double error = int.MaxValue;
        int sum = 0;
        for (int i = 0; i < nums.Length - 2; i++)
            for (int j = i + 1; j < nums.Length - 1; j++)
                for (int k = j + 1; k < nums.Length; k++)
                {
                    if (Math.Abs(nums[i] + nums[j] + nums[k] - target) < error)
                    {
                        sum = nums[i] + nums[j] + nums[k];
                        error = Math.Abs(sum - target);                        
                    }
                }
        return sum;        
    }
}

第二种:利用 排序 + 三索引 的方法

C# 实现

  • 状态:通过
  • 125 / 125 个通过测试用例
  • 执行用时: 132 ms, 在所有 C# 提交中击败了 100.00% 的用户
  • 内存消耗: 24 MB, 在所有 C# 提交中击败了 5.55% 的用户
public class Solution 
{
    public int ThreeSumClosest(int[] nums, int target) 
    {
        nums = nums.OrderBy(a => a).ToArray();
        int result = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.Length - 2; i++)
        {
            int start = i + 1, end = nums.Length - 1;
            while (start < end)
            {
                int sum = nums[start] + nums[end] + nums[i];
                if (Math.Abs(target - sum) < Math.Abs(target - result))
                    result = sum;
                if (sum > target)
                    end--;
                else if (sum < target)
                    start++;
                else
                    return result;
            }
        }
        return result;        
    }
}

Pyhton 实现

  • 执行结果:通过
  • 执行用时:124 ms, 在所有 Python3 提交中击败了 72.19% 的用户
  • 内存消耗:13.2 MB, 在所有 Python3 提交中击败了 22.06% 的用户
class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums = sorted(nums)
        result = nums[0] + nums[1] + nums[2]
        for i in range(0, len(nums) - 2):
            start = i + 1
            end = len(nums) - 1
            while start < end:
                sum = nums[start] + nums[end] + nums[i]
                if abs(target - sum) < abs(target - result):
                    result = sum
                if sum > target:
                    end -= 1
                elif sum < target:
                    start += 1
                else:
                    return result
        return result

20 有效的括号

  • 题号:20
  • 难度:简单
  • https://leetcode-cn.com/problems/valid-parentheses/

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

  • 左括号必须用相同类型的右括号闭合。
  • 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true

示例 6:

输入: ""
输出: true

示例 7:

输入: "(("
输出: false

实现

利用栈

思路:首先判断该字符串长度的奇偶性,如果是奇数,则返回false。否则,利用栈先进后出的特点,遇到“{”,“[”,“(”进行入栈操作,遇到“}”,“]”,“)”就与栈顶元素进行比较,如果是对应括号则出栈,否则返回false。

C# 语言

  • 执行结果:通过
  • 执行用时:88 ms, 在所有 C# 提交中击败了 70.31% 的用户
  • 内存消耗:22 MB, 在所有 C# 提交中击败了 17.91% 的用户
public class Solution {
    public bool IsValid(string s) 
    {
        if (string.IsNullOrEmpty(s))
            return true;

        int count = s.Length;
        if(count%2 == 1)
            return false;
            
        Stack<char> stack = new Stack<char>();
        for (int i = 0; i < count; i++)
        {
            char c = s[i];
            if (stack.Count == 0)
            {
                stack.Push(c);
            }
            else if(c == '[' || c == '{' || c == '(')
            {
                stack.Push(c);
            }
            else if (stack.Peek() == GetPair(c))
            {
                stack.Pop();
            }
            else
            {
                return false;
            }
        }
        return stack.Count == 0;        
    }
    
    public static char GetPair(char c)
    {
        if (c == ')')
            return '(';
        if (c == '}')
            return '{';
        if (c == ']')
            return '[';
        return '\0';
    }    
}

Python 语言

  • 执行结果:通过
  • 执行用时:40 ms, 在所有 Python3 提交中击败了 47.30% 的用户
  • 内存消耗:13.5 MB, 在所有 Python3 提交中击败了 5.16% 的用户
class Solution:
    def isValid(self, s: str) -> bool:
        dic = {")": "(", "}": "{", "]": "["}
        if s is None:
            return True
            
        count = len(s)
        if count % 2 == 1:
            return False
            
        lst = list()
        for i in range(count):
            c = s[i]
            if len(lst) == 0:
                lst.append(c)
            elif c == "[" or c == "{" or c == "(":
                lst.append(c)
            elif lst[-1] == dic[c]:
                lst.pop()
            else:
                return False
        return len(lst) == 0

21 合并两个有序列表

  • 题号:21
  • 难度:简单
  • https://leetcode-cn.com/problems/merge-two-sorted-lists/

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

实现

C# 实现

  • 执行结果:通过
  • 执行用时:108 ms, 在所有 C# 提交中击败了 83.80% 的用户
  • 内存消耗:25.9 MB, 在所有 C# 提交中击败了 5.85% 的用户
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution
{
    public ListNode MergeTwoLists(ListNode l1, ListNode l2)
    {
        ListNode pHead = new ListNode(int.MaxValue);
        ListNode temp = pHead;

        while (l1 != null && l2 != null)
        {
            if (l1.val < l2.val)
            {
                temp.next = l1;
                l1 = l1.next;
            }
            else
            {
                temp.next = l2;
                l2 = l2.next;
            }
            temp = temp.next;
        }

        if (l1 != null)
            temp.next = l1;

        if (l2 != null)
            temp.next = l2;

        return pHead.next;
    }
}

Python 实现

  • 执行结果:通过
  • 执行用时:40 ms, 在所有 Python3 提交中击败了 68.12% 的用户
  • 内存消耗:13.4 MB, 在所有 Python3 提交中击败了 17.11% 的用户
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        pHead = ListNode(None)
        temp = pHead
        while(l1 and l2):
            if (l1.val <= l2.val):
                temp.next = l1                
                l1 = l1.next
            else :
                temp.next = l2
                l2 = l2.next
            temp = temp.next
             
        if l1 is not None:
            temp.next = l1 
        else :
            temp.next = l2
            
        return pHead.next 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值