首页 > 其他 > 详细

LeetCode 1.Two Sum

时间:2016-11-01 01:11:27      阅读:184      评论:0      收藏:0      [点我收藏+]
        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;
        }

 

LeetCode 1.Two Sum

原文:http://www.cnblogs.com/pengdotnet/p/Two-Sum.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!