Leetcode 1: 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 var output = new int[2]; 4 var dict = new Dictionary<int, int>(); 5 6 for (int i = 0; i < nums.Length; i++) 7 { 8 if (dict.ContainsKey(target - nums[i])) 9 { 10 output[0] = dict[target - nums[i]]; 11 output[1] = i; 12 13 return output; 14 } 15 16 dict[nums[i]] = i; 17 } 18 19 return output; 20 } 21 }

浙公网安备 33010602011771号