zoukankan      html  css  js  c++  java
  • LeetCode 1. Two Sum

    给定一个整数数组,返回两个数字的索引,使得它们加起来等于一个特定的目标值。
    
    您可以假设每个输入都有一且只有一个答案,数组中每个元素只能使用一次。
    
    Example:
    
    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
    

      

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                            int[] nums = { 7, 11, 15 ,2};
    
                            int target = 9;
    
                            var numarr = TwoSum(nums, target);
    
            }
            // right hash: time O(n) (degenerate when collison occured) ususlly O(1) (insert and search) space: O(n) result: 496ms
            public static  int[] TwoSum(int[] nums, int target)
            {

    int[] result = new int[2]; //[0,3],[3,0]
    Dictionary<int, int> table = new Dictionary<int,int>(); // use empty constructor, result: 544 ms
    for (int i = 0; i < nums.Length; i++)
    {
    int another = target - nums[i];
    if (table.ContainsKey(another))
    {
    int anotherIndex = table[another];
    result[0] = anotherIndex > i ? i : anotherIndex;
    result[1] = anotherIndex < i ? i : anotherIndex;
    return result;
    }
    else
    {
    if (!table.ContainsKey(nums[i]))
    {
    table.Add(nums[i], i);
    }
    }
    }

    throw new Exception("no answer");

            }
        }
    }
    

      

  • 相关阅读:
    AcWing 900. 整数划分
    AcWing 913. 排队打水
    AcWing 897. 最长公共子序列
    AcWing 895. 最长上升子序列
    AcWing 902. 最短编辑距离
    AcWing 338. 计数问题
    AcWing 896. 最长上升子序列 II
    AcWing 779. 最长公共字符串后缀
    AcWing 282. 石子合并
    ASP.NET里常用的JS (转贴)
  • 原文地址:https://www.cnblogs.com/c-x-a/p/8144870.html
Copyright © 2011-2022 走看看