两数之和

两数之和

 
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
 
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
 
示例:
 
给定 nums = [2, 7, 11, 15], target = 9
 
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
 
来源:力扣(LeetCode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
 
 
using System;
using System.Collections.Generic;

namespace Wrox
{
    public class TwoNum
    {
        static void Main()
        {
            Solution s = new Solution();
            int[] result = new int[2];
            int[] nums = new int[10];
            int target = 9;
            for (int i = 0; i < 10; i++)
            {
                nums[i] = int.Parse(Console.ReadLine());
            }
            result = s.soluteByHash(nums, target);
            Console.WriteLine("[" + result[0] + "," + result[1] + "]");
            Console.ReadLine();
            return;
        }
    }
    public class Solution
    {
        public int[] solueTwoNum(int[] nums, int target)            //暴力破解
        {
            int Length = nums.Length;
            int[] result = new int[2];
            int flag = 1;
            for (int i = 0; i < Length - 1; i++)
            {
                for (int j = 1; j < Length; j++)
                {
                    if (nums[i] + nums[j] == target)
                    {
                        result[0] = i;
                        result[1] = j;
                        flag = 0;
                    }
                    if (flag == 0)
                        break;
                }
                if (flag == 0)
                    break;
            }
            return result;
        }
        public int[] soluteByHash(int[] nums,int target)           //一遍哈希表
        {
            var dic = new Dictionary<int, int>();
            for(int i = 0; i < nums.Length; i++)
            {
                var currentNum = nums[i];
                var temp = target - nums[i];                       //target减去当前数据得到temp
                if (dic.ContainsKey(temp))                         //temp若在字典中存在则有匹配值,返回下标
                {
                    return new int[] { dic[temp], i };
                }
                else if (!dic.ContainsKey(currentNum))             //当前数据不在字典中,则添加进字典
                {
                    dic.Add(currentNum,i);
                }
            }
            return null;
        }
    }
}

 

 

 

posted @ 2019-09-24 20:23  AsahiLock  阅读(315)  评论(3编辑  收藏  举报