标签:
1 using System; 2 using System.Collections.Generic; 3 using System.Globalization; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace LeetCode 9 { 10 class TwoSum 11 { 12 /// <summary> 13 /// via Hash 14 /// O(n) 15 /// </summary> 16 /// <param name="nums"></param> 17 /// <param name="targe"></param> 18 /// <returns></returns> 19 public int[] SolutionA(int[] nums, int target) 20 { 21 Dictionary<int,int> dic = new Dictionary<int, int>(); 22 for (int i = 0; i < nums.Length; i++) 23 { 24 if (dic.ContainsKey(target - nums[i])) 25 { 26 return new int[2] {dic[target-nums[i]]+1,i+1}; 27 } 28 else if(!dic.ContainsKey(nums[i])) 29 { 30 dic.Add(nums[i],i); 31 } 32 } 33 return null; 34 } 35 36 /// <summary> 37 /// O(nlogn) + O(n) + O(n) = O(nlogn) 38 /// </summary> 39 /// <param name="nums"></param> 40 /// <param name="target"></param> 41 /// <returns></returns> 42 public int[] SolutionB(int[] nums, int target) 43 { 44 int left = 0; 45 int right = nums.Length-1; 46 int[] tempArr = new int[nums.Length]; 47 nums.CopyTo(tempArr,0); 48 Array.Sort(tempArr); 49 while (left < right) 50 { 51 if (tempArr[left] + tempArr[right] < target) 52 { 53 left++; 54 continue; 55 }else if (tempArr[left] + tempArr[right] > target) 56 { 57 right--; 58 continue; 59 60 } 61 else 62 { 63 break; 64 } 65 } 66 int numA = tempArr[left]; 67 int numB = tempArr[right]; 68 int index1 = -1; 69 int index2 = -1; 70 int temp=0; 71 for (int i = 0; i < nums.Length; i++) 72 { 73 if (nums[i] == numA || nums[i] == numB) 74 { 75 if (index1 == -1) 76 { 77 index1 = i + 1; 78 temp = nums[i]; 79 } 80 else if (nums[i]==(target-temp)) 81 { 82 index2 = i + 1; 83 break; 84 } 85 } 86 } 87 return new int[2] {index1,index2}; 88 } 89 } 90 }
标签:
原文地址:http://www.cnblogs.com/HuoAA/p/4714362.html