Leetcode热题100

题目

1.两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。

你可以按任意顺序返回答案。

具体实现

暴力求解

思路及算法:
枚举数组中的每一个数 x,寻找数组中是否存在 target - x,即两数之和等于目标值。
此处想到的优化策略是,二层循环时(即 int j)可以从当前 i 后一位进行判断,因为第一遍循环时,已经判断过 i 和 j 的和了,反过来不再进行判断,也就提升了代码执行效率。

int[] nums = new int[] { 2, 7, 11, 15 };
int[] nums1 = new int[] { 3, 2, 4 };
int[] nums2 = new int[] { 3, 3 };

private int[] SumTwoNumber(int[] nums, int target)
{
    int[] result = new int[2];
    for (int i = 0; i < nums.Length - 1; i++)
    {
        for (int j = i + 1; j < nums.Length; j++)
        {
            if (nums[i] + nums[j] == target)
            {
                result[0] = i;
                result[1] = j;
                return result;
            }
        }
    }
    return result;
}

哈希表求解

思路及算法:
1、循环遍历数组,创建哈希表进行存储
2、判断此时哈希表中是否存在 target - nums[i] (即目标值减去当前遍历值)
若存在,可以直接返回target - nums[i] (即目标值减去当前遍历值)的索引 和当前值的索引
若不存在,将当前值添加到哈希表中(需要判断是否有重复数据)

int[] nums = new int[] { 2, 7, 11, 15 };
int[] nums1 = new int[] { 3, 2, 4 };
int[] nums2 = new int[] { 3, 3 };

private int[] SumTwoNumber2(int[] nums, int target)
{
    Dictionary<int, int> result = new Dictionary<int, int>();
    for (int i = 0; i < nums.Length; i++)
    {
        if (result.ContainsKey(target - nums[i]))
        {
            return new int[] { result[target - nums[i]], i };
        }
        else
        {
            result.TryAdd(nums[i], i);
        }
    }
    return null;
}
### LeetCode 100 LeetCode 上的目列表通常包含了社区中最受欢迎和频繁被讨论的问。这些目不仅有助于提升编程技能,也是求职者准备技术面试的重要资源。 #### 两数之和 该问是关于在一个整数数组中寻找两个数,使它们的和等于给定的目标数值[^1]。 ```python def two_sum(nums, target): num_to_index = {} for index, num in enumerate(nums): another_num = target - num if another_num in num_to_index: return [num_to_index[another_num], index] num_to_index[num] = index return [] ``` #### 合并两个有序链表 此问涉及将两个升序链表合并为一个新的升序链表,新链表由原两个链表中的节点组成。 ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def merge_two_lists(l1, l2): dummy = cur = ListNode(0) while l1 and l2: if l1.val < l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 or l2 return dummy.next ``` #### 最长回文子串 这个问旨在找出字符串 `s` 中最长的回文子串。解决方案可以基于中心扩展方法或动态规划实现[^2]。 ```python def longest_palindromic_substring(s): if not s: return "" start, end = 0, 0 for i in range(len(s)): len1 = expand_around_center(s, i, i) len2 = expand_around_center(s, i, i + 1) max_len = max(len1, len2) if max_len > end - (max_len - 1) // 2 end = i + max_len // 2 return s[start:end + 1] def expand_around_center(s, left, right): L, R = left, right while L >= 0 and R < len(s) and s[L] == s[R]: L -= 1 R += 1 return R - L - 1 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值