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;
    }
}
相关推荐
wallflower20201 小时前
滑动窗口算法在前端开发中的探索与应用
前端·算法
林木辛1 小时前
LeetCode热题 42.接雨水
算法·leetcode
MicroTech20251 小时前
微算法科技(NASDAQ: MLGO)采用量子相位估计(QPE)方法,增强量子神经网络训练
大数据·算法·量子计算
星梦清河1 小时前
宋红康 JVM 笔记 Day15|垃圾回收相关算法
jvm·笔记·算法
货拉拉技术2 小时前
揭秘语音交互的核心技术
算法
矛取矛求2 小时前
日期类的实现
开发语言·c++·算法
ISDF-工软未来2 小时前
C# 泛型简单案例
c#
在下雨5993 小时前
项目讲解1
开发语言·数据结构·c++·算法·单例模式
Jayyih3 小时前
嵌入式系统学习Day36(简单的网页制作)
学习·算法
脑洞代码3 小时前
20250909的学习笔记
算法