[1] power button and two numbers

 

Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.

You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.

Example:

Given nums = [2, 7, 11, 15], target = 9

Because nums [0] + nums [1 ] = 2 + 7 = 9
is returned [0, 1]

 

A violent solution (two-cycle)

     static int[] TwoSum(int[] nums, int target)
        {
            for (int i = 0; i < nums.Length; i++)
            {
                for (int j = i + 1; j < nums.Length; j++)
                {
                    if (nums[j] == target - nums[i])
                    {
                        return new int[] { i, j };
                    }

                }
            }
           return null;
        }

 

Second, use dictionary

c # hash table can not duplicate key inserted

If as a key element in the array will throw an exception

 static int[] TwoSum(int[] nums, int target)
        {
            var dictionary = new Dictionary<int, int>();
            for(int i = 0; i < nums.Length; i++)
            {
                int temp = target - nums[i];
                if (dictionary.Keys.Contains(temp))
                    return new int[] {dictionary[temp]+1,i+1 };
                dictionary[nums[i]] = i;
               
            }
            return null;


        }

 

Guess you like

Origin www.cnblogs.com/h-jang/p/11811134.html