您的位置:首页 > 其它

twoSum

2018-02-11 16:29 246 查看
given an array of Integers ,find two numbers such that they add up to a specific target number.
The function twoNum should return indices of the two numbers such that they add up to the targer, where index1 must be less than index2 Please note that your returned answers (both index1 and index2) are not zero-based.
code example 1:
   /// <summary>
        /// given an array of integers, find two numbers such that they add up to a specific target number 
        /// the function TwoSum should return indices of the two numbers such that they add up to the target ,where index1 must be less than index2, Please note that your returned answers (both index1 and index2 ) are non-zero-based.
        /// You may assume that each input would have exactly one solution.
        /// </summary>
        /// <param name="num"></param>
        /// <param name="targetnum"></param>
        /// <returns></returns>
        static int[] Method_5(int[] num,int targetnum)
        {
            Dictionary<int, int> dictionary = new Dictionary<int, int>();

            for(int i = 0; i < num.Length; i++)
            {
                dictionary.Add(num[i], i);
            }

            for(var i=0;i<num.Length;i++)
            {
                if (dictionary.Keys.Contains(targetnum - i))
                {
                    int v = dictionary[targetnum - i];
                    if (v != null && v > i)
                    {
                        return new int[] { i + 1, v + 1 };
                    }
                }
               
            }
            return null;

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法