标签:
题目描述:public class Solution { public int[] TwoSum(int[] nums, int target) { var hash = new Dictionary<int, int>(); for(var i = 0;i < nums.Length; i++){ if(!hash.ContainsKey(nums[i])){ hash.Add(nums[i], i); } else{ if(target == nums[i] * 2){ return new int[2]{hash[nums[i]] + 1, i + 1}; } // if one number appears twice and not equals to target half , just take the first one } } foreach(var k in hash.Keys){ var k2 = target - k; if(hash.ContainsKey(k2) && hash[k2] != hash[k]){ var index1 = hash[k]; var index2 = hash[k2]; if(index1 > index2){ return new int[2]{index2 + 1, index1 + 1}; }else{ return new int[2]{index1 + 1, index2 + 1}; } } } return null; } }
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/50144879