马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

两数之和

[复制链接]
查看1882 | 回复0 | 2019-9-26 09:22:20 | 显示全部楼层 |阅读模式

两数之和

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

092248lggq1aqqz3qc1ntj.png







来源:https://www.cnblogs.com/asahiLikka/archive/2019/09/24/11580761.html
C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则