LeetCode 1.Two Sum

        public static int[] TwoSum(int[] nums, int target)
        {
            int[] result = new int[2];
            //key为数值,value为它的索引值
            Dictionary<int, int> temp = new Dictionary<int, int>();
            for (int i = 0; i < nums.Length; i++)
            {
                int n;
                //判断nums[i]是否在字典里,不在加入
                bool exist = temp.TryGetValue(nums[i], out n);
                if (!exist)
                {
                    temp.Add(nums[i], i);
                }
                //判断target - nums[i]是否在字典里,在的话并且n与i不相等;返回
                bool exist2 = temp.TryGetValue(target - nums[i], out n);
                if (exist2 && n < i)
                {
                    result[0] = n;
                    result[1] = i;
                    return result;
                }
            }
            return result;
        }

 

posted @ 2016-10-31 23:41  pzhang22  阅读(141)  评论(0编辑  收藏  举报