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");
    }

    }

  • 相关阅读:
    Eclipse中的常见设置
    Maven配置及使用总结
    启动Eclipse时,出现 “Failed to load the JNI shared library "C:Program Filesjavajdk1.7.....jvm.dll"
    Java 环境问题汇总
    Java 异常处理
    Java面向对象(二)
    Java面向对象(一)
    Java获取路径
    Java代码读取文件
    工作常用快捷键大全
  • 原文地址:https://www.cnblogs.com/coderblog/p/10438137.html
Copyright © 2011-2022 走看看