设为首页 加入收藏

TOP

两数之和
2019-09-25 11:18:18 】 浏览:52
Tags:两数 之和

两数之和

 

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

 

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

 

示例:

 

给定 nums = [2, 7, 11, 15], target = 9

 

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

 

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/two-sum

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 1 using System;
 2 namespace Wrox
 3 {
 4     public class TwoNum
 5     {
 6         static void Main()
 7         {
 8             Solution s = new Solution();
 9             int[] result = new int[2];
10             int[] nums = new int[10];
11             int target = 9;
12             for (int i = 0; i < 10; i++)
13             {
14                 nums[i] = int.Parse(Console.ReadLine());
15             }
16             result = s.solueTwoNum(nums, target);
17             Console.WriteLine("[" + result[0] + "," + result[1] + "]");
18             Console.ReadLine();
19             return;
20         }
21     }
22     public class Solution
23     {
24         public int[] solueTwoNum(int[] nums, int target)
25         {
26             int Length = nums.Length;
27             int[] result = new int[2];
28             int flag = 1;
29             for (int i = 0; i < Length - 1; i++)
30             {
31                 for (int j = 1; j < Length; j++)
32                 {
33                     if (nums[i] + nums[j] == target)
34                     {
35                         result[0] = nums[i];
36                         result[1] = nums[j];
37                         flag = 0;
38                     }
39                     if (flag == 0)
40                         break;
41                 }
42                 if (flag == 0)
43                     break;
44             }
45             return result;
46         }
47     }
48 }

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇asp.net core系列 73 Exceptionle.. 下一篇C#基础之委托

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目