LeetCode算法题(C#版)

两数之和

方法一:暴力枚举

cs 复制代码
class Solution {
    public int[] TwoSum(int[] nums, int target) {
        for(int i=0;i<nums.Length;i++){
            for(int j=i+1;j<nums.Length;j++){
                if(nums[i]+nums[j]==target){
                    return new int[]{i,j};
                }
            }
        }
        return new int[0];
    }
}

方法二:C#知识中的字典

cs 复制代码
class Solution {
    public int[] TwoSum(int[] nums, int target) {
        Dictionary<int, int> hashtable = new Dictionary<int, int>();
        for (int i = 0; i < nums.Length; ++i) {
            if (hashtable.ContainsKey(target - nums[i])) {
                return new int[]{hashtable[target - nums[i]], i};
            }
            hashtable[nums[i]]=i;
        }
        return new int[0];
    }
}
回文数

代码

cs 复制代码
public class Solution {
    public bool IsPalindrome(int x) {
        int revertedNumber=0;
        if(x<0||(x>0&&x%10==0)){
            return false;
        }
        while(x>revertedNumber){
            revertedNumber=revertedNumber*10+x%10;
            x=x/10;
        }
        return x==revertedNumber||x==revertedNumber/10;
    }
}
罗马数组转整数

代码

cs 复制代码
public class Solution {
    public int RomanToInt(string s) {
        Dictionary<char,int> romanToInt=new Dictionary<char,int>();
        romanToInt.Add('I',1);
        romanToInt.Add('V',5);
        romanToInt.Add('X',10);
        romanToInt.Add('L',50);
        romanToInt.Add('C',100);
        romanToInt.Add('D',500);
        romanToInt.Add('M',1000);
        int answer=0;
        for(int i=0;i<s.Length;i++){
            int value=romanToInt[s[i]];
            if(i<s.Length-1&&value<romanToInt[s[i+1]]){
                answer-=value;
            }
            else{
                answer+=value;
            }
        }
        return answer;
    }
}
构成整天的下标对数目I

代码

和两数之和的逻辑相同

cs 复制代码
public class Solution {
    public int CountCompleteDayPairs(int[] hours) {
        int sum=0;
        for(int i=0;i<hours.Length;i++){
            for(int j=i+1;j<hours.Length;j++){
                if((hours[i]+hours[j])%24==0){
                    sum++;
                }
            }
        }
        return sum;
    }
}
相关推荐
aaaameliaaa7 小时前
字符函数和字符串函数
c语言·笔记·算法
城管不管8 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
月疯9 小时前
二分法算法(水平等分图形面积)
算法
豆瓣鸡9 小时前
算法日记 - Day3
java·开发语言·算法
白白白小纯9 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
Achou.Wang9 小时前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
凯丨9 小时前
AI 蠕虫来了:恶意文档如何通过 Copilot for Word 自我传播?
人工智能·c#·copilot
The Chosen One9859 小时前
高进度算法模板速记(待完善)
java·前端·算法
Aaron - Wistron10 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
骊城英雄12 小时前
基于C#+avalonia ui实现的跨平台点胶机灌胶监控控制上位机软件
开发语言·ui·c#