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

    }

  • 相关阅读:
    Flask中路由系统、Flask的参数及app的配置
    linux之master和minion
    linux之docker学习
    项目的发布(nginx、uwsgi、django、virtualenv、supervisor)
    Linux下安装和使用nginx
    linux下主从同步和redis的用法
    论图像识别的预处理技术
    图像技术分析 图像编辑器核心技术
    C++ Primer 第九章 顺序容器
    图像灰度化公式 颜色空间用途说明
  • 原文地址:https://www.cnblogs.com/coderblog/p/10438137.html
Copyright © 2011-2022 走看看