兩數之和算法(C#)

兩數之和算法(C#)

給定一個整數數組 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 }

 

相關文章
相關標籤/搜索