LeetCode算法题解

阅读“关于 2 分钟

Hi! :hand:

LeetCode 第一道题: Two Sum,难度简单。

Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

 1 public class Solution {
 2     public int[] TwoSum(int[] nums, int target) {
 3         int[] res = new int[2];
 4         Dictionary<int, int> d = new Dictionary<int, int>();
 5         for (int i = 0; i < nums.Length; ++i)
 6         {
 7             if (d.ContainsKey(nums[i]))
 8             {
 9                 res[0] = d[nums[i]];
10                 res[1] = i;
11                 return res;
12             }
13             d[target - nums[i]] = i;
14         }
15         return res;
16     }
17 }

Gist code


To use, see:Jektify - Doc

jektify © 2019  +

Música

Goodbye! :wink:


The word of the day!

Put a very powerful message.