LeetCode--C#版本

1. 两数相加

using System;
namespace Qusetion
{
    class Solution
    {
        static 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, 0 };
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            int[] term = { 1, 2, 3, 6 };
            int [] tempt;
            tempt = Solution.TwoSum(term, 9);
            Console.WriteLine($"{tempt[0]},{ tempt[1]}");
            
        }
    }
}

2.学习哈希函数

重点是实现从数据到存储位置的一一映射

把数据的属性放在数组中---哈希表/散列表,每个索引处的位置称为桶(bucket),可以存储一个或多个键-值对。哈希表的关键特点是快速的插入、查找和删除操作

using System.Collections.Generic;
using System;
namespace Sum
{
    static public class Solution
    {
        static public int[] TwoSum(int[] nums, int target)
        {
            int[] result = new int[2];
            //创建一个字典用于存储每个数字及其出现的次数
            Dictionary<int, int> dic = new Dictionary<int, int>();
            //遍历数组
            for(int i = 0; i < nums.Length; i++)
            {
                if (dic.ContainsKey(nums[i]))
                {
                    //如果字典中已经包含该数字--出现次数加一
                    dic[nums[i]] += 1;
                }
                else
                {
                    //如果没出现过,那就初始化为0
                    dic[nums[i]] = 0;
                }
            }
            //再次遍历
            for(int i = 0; i < nums.Length; i++)
            {
                if (nums.Contains(target - nums[i]))
                {
                    //如果数组中存在目标值减去当前数字的差值
                    //则将当前索引赋值给数组第一个位置
                    result[0] = i;
                    //使用ToList()将数组变为列表
                    //使用FindIndex()找到差值的索引
                    result[1] = nums.ToList().FindIndex(item => item == target - nums[i]);
                    if (result[0] != result[1])
                    {
                        break;
                    }
                }
            }
            return result;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int[] terms = { 1, 2, 3, 6 };
            int[] tempt;
            tempt = Solution.TwoSum(terms, 9);
            Console.WriteLine($"{tempt[0]},{tempt[1]}");
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值