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;
    }
}
相关推荐
hetao17338373 小时前
2026-10-03~04 hetao1733837 的刷题记录
c++·算法
Zootopia6264 小时前
飞行力学知识梳理1|飞行性能与稳定性
人工智能·python·算法·机器学习·无人机·学习方法·信息与通信
longlongzihan4 小时前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
2601_960356385 小时前
2027校招采购岗解析:数学基础如何迁移到需求预测、成本与供应商分析
人工智能·算法
周杰伦fans6 小时前
8GB显存下模型量化实战指南
人工智能·后端·c#
h_a_o777oah6 小时前
【树论】树链剖分:将树形结构转化为线性结构以处理树上路径问题(洛谷 P3384 附C++代码模板)
数据结构·算法·线段树·acm·树链剖分·树论·重链剖分
HEJOO96 小时前
指针的算术运算详解
java·数据结构·算法
Coder-magician6 小时前
《代码随想录》刷题打卡day47:并查集-part01
数据结构·算法·图论
垆边人似月.6 小时前
VLAN 资源池(100~200 分档)
数据结构·算法
潼心1412o7 小时前
C++初阶(长期更新)第6讲:类和对象(下)
开发语言·c++·算法