zoukankan      html  css  js  c++  java
  • 2、两数之和

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

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

    示例:

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

    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

    解答:

    C#

    class Program

    {

    static void Main(string[] args)
    {
      int[] nums = { 2, 7, 11, 15 };
      int target = 9;

      var arr = OneSum(nums, target);
      //var arr = TwoSum(nums, target);
      //var arr = ThreeSum(nums, target);

      for (int i = 0; i < arr.Length; i++)
      {
        Console.WriteLine(arr[i]);
      }

      Console.ReadKey();
    }

    //第一种方法
    public static int[] OneSum(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 };
          }
        }
      }

      throw new Exception("No two sum solution");
    }
    //第二种方法
    public static int[] TwoSum(int[] nums, int target)
    {
      Hashtable ht = new Hashtable();
      for (int i = 0; i < nums.Length; i++)
      {
        ht.Add(nums[i], i);
      }

      for (int i = 0; i < nums.Length; i++)
      {
        int complent = target - nums[i];

        if (ht.ContainsKey(complent) && Convert.ToInt32(ht[complent]) != i)
        {
          return new int[] { i, Convert.ToInt32(ht[complent]) };
        }
      }

      throw new Exception("No two sum solution");
    }

    //第三种方法
    public static int[] ThreeSum(int[] nums, int target)
    {
      Hashtable ht = new Hashtable();
      for (int i = 0; i < nums.Length; i++)
      {
        int complent = target - nums[i];

        if (ht.ContainsKey(complent))
        {
          return new int[] { Convert.ToInt32(ht[complent]), i};
        }

        ht.Add(nums[i], i);
      }

      throw new Exception("No two sum solution");
    }

    }

  • 相关阅读:
    计算机中的进制和编码
    操作系统简史
    电脑结构和CPU、内存、硬盘三者之间的关系
    电脑简史
    使用开源my-deploy工具实现开发环境的代码自动化部署
    使用Let’s Encrypt创建nginx免费SSL证书
    VM ESXI 服务器虚拟化资料积累
    python mysql连接函数
    python日期格式转换小记
    Python模块学习
  • 原文地址:https://www.cnblogs.com/coderblog/p/10438137.html
Copyright © 2011-2022 走看看