Hi!
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 }
To use, see:Jektify - Doc
Goodbye!
Put a very powerful message.