(一)算法


文章目录

  • 项目地址
  • 一、题目
    • [1.1 基础题](#1.1 基础题)
      • [1. 反转字符串](#1. 反转字符串)
      • [2. 判断回文字符串](#2. 判断回文字符串)
      • [3. 两个数组的交集](#3. 两个数组的交集)
      • [4. 字符串中第一个不重复的字符](#4. 字符串中第一个不重复的字符)
      • [5. LRU 缓存机制 (经典 OOD 题)](#5. LRU 缓存机制 (经典 OOD 题))
      • [6. 写一个线程安全的 有界队列](#6. 写一个线程安全的 有界队列)
      • [7. 实现一个 LINQ 的 Where 扩展方法](#7. 实现一个 LINQ 的 Where 扩展方法)
      • [8. 并发请求控制](#8. 并发请求控制)
    • [9. 设计 TinyUrl 系统](#9. 设计 TinyUrl 系统)

项目地址

  • 教程作者:
  • 教程地址:
复制代码
  • 代码仓库地址:
复制代码
  • 所用到的框架和插件:

    dbt
    airflow

一、题目

1.1 基础题

1. 反转字符串

输入 "hello",输出 "olleh"。

要求:不能直接用 Array.Reverse。

cs 复制代码
string ReverseString(string input)
{
    if (string.IsNullOrEmpty(input)) return input;

    char[] arr = input.ToCharArray();
    int left = 0, right = arr.Length - 1;

    while (left < right)
    {
        (arr[left], arr[right]) = (arr[right], arr[left]);
        left++;
        right--;
    }

    return new string(arr);
}

2. 判断回文字符串

输入 "abba" 返回 true,输入 "abc" 返回 false。

cs 复制代码
bool IsPalindrome(string input)
{
    if (string.IsNullOrEmpty(input)) return true;

    int left = 0, right = input.Length - 1;
    while (left < right)
    {
        while (left < right && !char.IsLetterOrDigit(input[left])) left++;
        while (left < right && !char.IsLetterOrDigit(input[right])) right--;

        if (char.ToLower(input[left]) != char.ToLower(input[right]))
            return false;

        left++;
        right--;
    }
    return true;
}

3. 两个数组的交集

输入 nums1 = [1,2,2,1],nums2 = [2,2] → 输出 [2,2]。

cs 复制代码
int[] Intersect(int[] nums1, int[] nums2)
{
    var dict = new Dictionary<int, int>();
    foreach (var n in nums1)
    {
        if (!dict.ContainsKey(n)) dict[n] = 0;
        dict[n]++;
    }

    var result = new List<int>();
    foreach (var n in nums2)
    {
        if (dict.ContainsKey(n) && dict[n] > 0)
        {
            result.Add(n);
            dict[n]--;
        }
    }

    return result.ToArray();
}

4. 字符串中第一个不重复的字符

输入 "leetcode" → 输出 l

输入 "aabb" → 输出 null 或特殊符号。

cs 复制代码
char? FirstUniqueChar(string s)
{
    var dict = new Dictionary<char, int>();
    foreach (var ch in s)
    {
        if (!dict.ContainsKey(ch)) dict[ch] = 0;
        dict[ch]++;
    }

    foreach (var ch in s)
    {
        if (dict[ch] == 1) return ch;
    }

    return null;
}

5. LRU 缓存机制 (经典 OOD 题)

要求:

Get O(1)

Put O(1)

超出容量时移除最近最少使用的元素。

cs 复制代码
public class LRUCache
{
    private readonly int _capacity;
    private readonly Dictionary<int, LinkedListNode<(int Key, int Value)>> _cache;
    private readonly LinkedList<(int Key, int Value)> _list;

    public LRUCache(int capacity)
    {
        _capacity = capacity;
        _cache = new Dictionary<int, LinkedListNode<(int, int)>>();
        _list = new LinkedList<(int, int)>();
    }

    public int Get(int key)
    {
        if (!_cache.TryGetValue(key, out var node))
            return -1;

        _list.Remove(node);
        _list.AddFirst(node);
        return node.Value.Value;
    }

    public void Put(int key, int value)
    {
        if (_cache.TryGetValue(key, out var node))
        {
            _list.Remove(node);
        }
        else if (_cache.Count >= _capacity)
        {
            var last = _list.Last;
            if (last != null)
            {
                _cache.Remove(last.Value.Key);
                _list.RemoveLast();
            }
        }

        var newNode = new LinkedListNode<(int, int)>((key, value));
        _list.AddFirst(newNode);
        _cache[key] = newNode;
    }
}

6. 写一个线程安全的 有界队列

cs 复制代码
public class BlockingQueue<T>
{
    private readonly Queue<T> _queue = new();
    private readonly int _capacity;
    private readonly object _lock = new();

    public BlockingQueue(int capacity) => _capacity = capacity;

    public void Enqueue(T item)
    {
        lock (_lock)
        {
            while (_queue.Count >= _capacity)
                Monitor.Wait(_lock);

            _queue.Enqueue(item);
            Monitor.PulseAll(_lock);
        }
    }

    public T Dequeue()
    {
        lock (_lock)
        {
            while (_queue.Count == 0)
                Monitor.Wait(_lock);

            var item = _queue.Dequeue();
            Monitor.PulseAll(_lock);
            return item;
        }
    }
}

7. 实现一个 LINQ 的 Where 扩展方法

  • 模拟实现 IEnumerable.Where
cs 复制代码
public static class MyLinqExtensions
{
    public static IEnumerable<T> MyWhere<T>(
        this IEnumerable<T> source,
        Func<T, bool> predicate)
    {
        foreach (var item in source)
        {
            if (predicate(item))
                yield return item;
        }
    }
}

8. 并发请求控制

写一个方法,接收一组 Func,限制同时最多执行 N 个任务,直到全部完成。

cs 复制代码
public async Task RunWithMaxConcurrency(IEnumerable<Func<Task>> tasks, int maxConcurrency)
{
    using SemaphoreSlim semaphore = new(maxConcurrency);
    var runningTasks = tasks.Select(async task =>
    {
        await semaphore.WaitAsync();
        try
        {
            await task();
        }
        finally
        {
            semaphore.Release();
        }
    });
    await Task.WhenAll(runningTasks);
}

9. 设计 TinyUrl 系统

输入长链接 "https://example.com/abc/def"

输出短链接 "http://tinyurl.com/xyz123"

要求短链接能还原为长链接。

cs 复制代码
public class TinyUrlService
{
    private readonly Dictionary<string, string> _map = new();
    private readonly string _baseUrl = "http://tinyurl.com/";
    private readonly Random _random = new();

    public string Encode(string longUrl)
    {
        var key = Guid.NewGuid().ToString("N").Substring(0, 6);
        _map[key] = longUrl;
        return _baseUrl + key;
    }

    public string Decode(string shortUrl)
    {
        var key = shortUrl.Replace(_baseUrl, "");
        return _map[key];
    }
}
相关推荐
2201_757830871 天前
全局异常处理器
java
aigcapi1 天前
RAG 系统的黑盒测试:从算法对齐视角解析 GEO 优化的技术指标体系
大数据·人工智能·算法
知远同学1 天前
Anaconda的安装使用(为python管理虚拟环境)
开发语言·python
小徐Chao努力1 天前
【Langchain4j-Java AI开发】09-Agent智能体工作流
java·开发语言·人工智能
CoderCodingNo1 天前
【GESP】C++五级真题(贪心和剪枝思想) luogu-B3930 [GESP202312 五级] 烹饪问题
开发语言·c++·剪枝
柯慕灵1 天前
7大推荐系统/算法框架对比
算法·推荐算法
adam-liu1 天前
Fun Audio Chat 论文+项目调研
算法·语音端到端·fun-audio-chat
Coder_Boy_1 天前
SpringAI与LangChain4j的智能应用-(理论篇3)
java·人工智能·spring boot·langchain
kylezhao20191 天前
第1章:第一节 开发环境搭建(工控场景最优配置)
开发语言·c#
啃火龙果的兔子1 天前
JavaScript 中的 Symbol 特性详解
开发语言·javascript·ecmascript