Leetcode 1, leetcode
Question
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
Solution
Public int [] TwoSum (int [] nums, int target) {# region solution 1, brute force cracking method int [] newInt = null; for (int I = 0; I <nums. length; I ++) {for (int j = I + 1; j <nums. length; j ++) {if (nums [I] + nums [j] = target) {newInt = new int [] {I, j };}}} return newInt; # endregion # region solution 2, dictionary <key, value> int [] arr = new int [2]; Dictionary <int, int> dict = new Dictionary <int, int> (); for (int I = 0; I <nums. length; I ++) {int cha = target-nums [I]; if (dict. containsKey (cha) {arr [0] = dict [cha]; arr [1] = I; break;} else {dict. add (nums [I], I) ;}return arr; # endregion}
Solution on OJ: https://leetcode.com/articles/two-sum/
The first leetcode is HashTable. in C #, It is Dictionary <key, value>.