【C#】Two Sum

Two Sum是LeetCode基础的演算法~

例如~ 有一个array放 7, 11, 5, 2~ 然後~target是9~

最後它的输出会是 0,3~


学习目标: Two sum的概念及实务

学习难度: ☆☆☆


using System;

using System.Collections.Generic;

namespace ConsoleApp1
{
    class MainProgram
    {
        static int[] Twosum(int[] numbers, int target)
        {
            //用Dictionary实作

            Dictionary<int, int> dictionary = new Dictionary<int, int>();

            for (int i = 0; i < numbers.Length; i++)
            {
                int temp = target - numbers[i];

                if (dictionary.ContainsKey(temp))
                {
                    //dictionary[temp]是key(数值),会回传value(索引)

                    return new int[] { dictionary[temp], i };
                }

                else
                {
                    // 因为我们要求索引,所以这里的value是i

                    dictionary[numbers[i]] = i;
                }
            }
            return null;
        }

        static void Main()
        {
            int[] arrays = new int[] { 7, 11, 5, 2 };

            int target = 9;

            Twosum(arrays, target);
        }
    }
}

参考资料:

https://ithelp.ithome.com.tw/articles/10217042


<<:  【JavaScript】阵列方法之some()

>>:  【C++】Stack and Queues

Day12 - 【概念篇】OAuth flows: flows这一小段路上路前注意事项

本系列文之後也会置於个人网站 其实我原本是想要 RESTer 干到底的哈?。 今天有一点是插话的。...

Day 29 注册ASN必要的几个object

那今天呢,我们来讲解一下请LIR注册ASN需要几个重要的Object 首先,我们这边是以RIPE为例...

SystemC: 月球转运站

创世神创造了世界,还觉得不够,又做了一颗月球。 过了两天觉得地球不够圆,决定把存在月球的 pi拿回来...

Day23-介接 API(一)Google Calendar(I)启用 API 与 Events——Create

大家好~ 接着一起来介接 API 吧! 今天先从 Google Calendar API 开始~ 上...

Day 26:v-if 才做选择,v-show 全都秀

目前的版面配置是基本的瀑布流效果,而此模式较着重在显示书本封面图片,一列只能出现三本书单,RWD 的...