给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。算法
你能够假设每种输入只会对应一个答案。可是,数组中同一个元素不能使用两遍。数组
你能够按任意顺序返回答案。网络
示例 1:spa
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:由于 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:code
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:blog
输入:nums = [3,3], target = 6
输出:[0,1]
leetcode
提示:get
2 <= nums.length <= 103
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案string
来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/two-sum
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。it
1 using System; 2
3 namespace ConsoleApp3 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 int[] arr = new int[2]; 10
11 Program program = new Program(); 12 int[] numbers = new int[] { 1, 2, 3,4,16,6,7,8,100}; 13 arr = program.TwoSum(numbers, 101); 14 } 15 public int[] TwoSum(int[] nums, int target) 16 { 17 int i = 0, t = 0; 18 int[] array = new int[2]; 19 bool isGet = false; 20 while (i < nums.Length) 21 { 22 //①判断是否重复,且 t 不能是数组最后一位数的数组下标,不然会由于t+=1,而超过数组合法范围
23 if (i == t && t != nums.Length - 1) 24 { 25 t += 1; 26 continue; 27 } 28 if (nums[i] + nums[t] == target) 29 { 30 //由于①,因此 在i与t在数组最后一位交汇时,会重复,因此直接跳过,由于咱们不取重复值,由于是在数组的末尾处交汇,后面已经没有须要尝试的 数 了,因此大胆直接跳过循环
31 if (i == t && i == nums.Length - 1 && t == nums.Length - 1) 32 break; 33 isGet = true; 34 array[0] = i; 35 array[1] = t; 36 Console.WriteLine("[{0},{1}]", i, t); 37 break; 38 } 39 else
40 { 41 if (t == nums.Length - 1) 42 { 43 i += 1; 44 t = 0; 45 continue; 46 } 47 t += 1; 48 } 49 } 50 if(isGet == false) 51 Console.WriteLine("The right number was not found."); 52 return array; 53 } 54 } 55 }