C#算法之兩數(shù)之和
題目
給定一個(gè)整數(shù)數(shù)組 nums
和一個(gè)目標(biāo)值 target
,請(qǐng)你在該數(shù)組中找出和為目標(biāo)值的那 兩個(gè) 整數(shù),并返回他們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會(huì)對(duì)應(yīng)一個(gè)答案。但是,你不能重復(fù)利用這個(gè)數(shù)組中同樣的元素。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因?yàn)?nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
提示:不能自身相加。
測(cè)試用例
[2,7,11,15]
9
預(yù)期結(jié)果
[0,1]
格式模板
public class Solution { public int[] TwoSum(int[] nums, int target) { /* 代碼 */ } }
筆者的代碼,僅供參考
使用暴力方法,運(yùn)行時(shí)間 700ms-1100ms
public class Solution { public int[] TwoSum(int[] nums, int target) { int [] a = new int[2]; for (int i = 0; i < nums.Length - 1; i++) { for (int j = i + 1; j < nums.Length; j++) { if (nums[i] + nums[j] == target) { a[0] = i; a[1] = j; } } } return a; } }
運(yùn)行時(shí)間 400ms-600ms
由于使用的是哈希表,所以缺點(diǎn)是鍵不能相同。
public class Solution { public int[] TwoSum(int[] nums, int target) { int[] a = new int[2]; System.Collections.Hashtable hashtable = new System.Collections.Hashtable(); for(int i = 0; i < nums.Length; i++) { hashtable.Add(nums[i], i); } for(int i = 0; i < nums.Length; i++) { int complement = target - nums[i]; if (hashtable.ContainsKey(complement) && int.Parse(hashtable[complement].ToString())!=i) { a[0] = i; a[1] = int.Parse(hashtable[complement].ToString()); } } return a; } }
還是哈希表,缺點(diǎn)是哈希表存儲(chǔ)的類型是object,獲取值時(shí)需要進(jìn)行轉(zhuǎn)換。
public int[] TwoSum(int[] nums, int target) { int[] a = new int[2]; System.Collections.Hashtable h = new System.Collections.Hashtable(); for (int i = 0; i < nums.Length; i++) { int c = target - nums[i]; if (h.ContainsKey(c)) { a[0] = int.Parse(h[c].ToString()) <= nums[i] ? int.Parse(h[c].ToString()) : i; a[1] = int.Parse(h[c].ToString()) > nums[i] ? int.Parse(h[c].ToString()) : i; } else if (!h.ContainsKey(nums[i])) { h.Add(nums[i], i); } } return a; }
抄一下別人的
public class Solution { public int[] TwoSum(int[] nums, int target) { int[] res = {0, 0}; int len = nums.Length; Dictionary<int, int> dict = new Dictionary<int, int>(); for (int i = 0; i < len; i++) { int query = target - nums[i]; if (dict.ContainsKey(query)) { int min = (i <= dict[query]) ? i : dict[query]; int max = (i <= dict[query]) ? dict[query] : i; return new int[] { min, max }; } else if (!dict.ContainsKey(nums[i])) { dict.Add(nums[i], i); } } return res; } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章

unity shader實(shí)現(xiàn)玻璃折射效果

Unity3D移動(dòng)端實(shí)現(xiàn)搖一搖功能

C#彈出對(duì)話框確定或者取消執(zhí)行相應(yīng)操作的實(shí)例代碼