两数之和

 

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

 

 

using System;

namespace LeetCode
{
    class Program
    {
        static void Main(string[] args)
        {
            Solution solution = new Solution();
            int[] arrs = solution.TwoSum(new int[] { 2, 3, 5, 6, 7 }, 11);
            foreach (var item in arrs)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }

    public class Solution
    {
        public int[] TwoSum(int[] nums, int target)
        {
            for (int i = 0; i < nums.Length; i++)
            {
                for (int j = 0; j < nums.Length; j++)
                {
                    if (i == j)
                    {
                        continue;
                    }
                    else
                    {
                        if (nums[i] + nums[j] == target)
                        {
                            
                            return new int[] { i, j };
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
            }
            //根据题目肯定有且只有一对,两个数之和等于目标数,所以执行不到这?
            return null;
        }
    }
}

 

 

 

 

posted @ 2020-05-28 12:09  富坚老贼  阅读(162)  评论(0)    收藏  举报