summaryrefslogtreecommitdiff
path: root/Assets/Algorithms/Algorithms_Utils.cs
blob: 6eee42fc680d58e949ef72a7fb75a2fb257a4eca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace AlgorithmCollection
{
    public static partial class Algorithms
    {
        // 两数之和,在nums中找到和为target的两个数
        public static int[] TwoSum(int[] nums, int target)
        {
            int a = 0, b = 0;
            Dictionary<int, int> lut = new Dictionary<int, int>();
            for (int i = 0; i < nums.Length; ++i)
            {
                if (lut.ContainsKey(target - nums[i]))
                {
                    a = i;
                    b = lut[target - nums[i]];
                    break;
                }
                lut.Add(nums[i], i);
            }
            return new int[] { a, b };
        }

        //

    }
}