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

    Description:

      Given an array of integers, return indices of the two numbers such that they add up to a specific target.

      You may assume that each input would have exactly one solution, and you may not use the same element twice.

    Example:

      Given nums = [2, 7, 11, 15], target = 9,
    
      Because nums[0] + nums[1] = 2 + 7 = 9,
      return [0, 1].

     

    思路分析:

      1.要得到答案,不可避免的是要遍历数组每个元素的,因为只有遍历了一遍才能确定各个元素是否存在另一个“搭档”(它与这个搭档的和为target);

      2.第一次遍历每个元素的时候,要想找到该元素的搭档,第一直觉是从当前元素起,再次遍历它后面的每个元素从而确定是否存在搭档;

      3.于是得出第一种解法:通过两层循环实现。

    改进:

      在第2步中,第一次遍历到特定元素的时候,为了找到其搭档,采用了第二次循环向后遍历的方式(牺牲时间),这个地方其实可以开始考虑第二种方式(牺牲空间),即不向后遍历了,引入一个数据结构,耗费一些空间来储存已经遍历了的数组记录,之后的遍历都会向前查找搭档(即在存储的记录中查找)。

      (*) 数据结构要求:既要记录值(判断是否是搭档的时候要相加求和),又要记录索引(输出结果需要的是索引)。于是,自然会选择键值对储存数据的结构,即哈希表。同时,因为我们是通过取值判断是否是搭档,然后通过值找索引。所以,方便起见,应该用键存储值,用值存储索引。


    C#实现:

      ”初级“解法:

    public class Solution {
        public int[] TwoSum(int[] nums, int target) {
            for(int i=0 ;i<nums.Length-1;i++){
                for(int j = i+1;j<nums.Length;j++){
                    if(nums[i]+nums[j]==target)
                        return new int[]{i,j};
                }            
            }
            return new int[]{-1,-1};
        }
    }
    
    

      “进阶”解法:

    public class Solution {
        public int[] TwoSum(int[] nums, int target) {
            int[] rst = {0,0};
            Hashtable ht = new Hashtable();
            for(int i=0 ;i<nums.Length;i++){
                int target2 = target-nums[i];
                if(ht.ContainsKey(target2)){
                    rst[0] = (int)ht[target2];
                    rst[1] = i;
                    return rst;
                }
           //重复的值不重复添加 
           if(!ht.ContainsKey(nums[i])) ht.Add(nums[i],i); }
    return rst; } }
  • 相关阅读:
    ubuntu16.04解决播放swf视频文件问题
    ubuntu下设置clion是使用clang和clang++
    Linux 下没有conio.h 已解决
    适合最新版docker自定义启动配置
    nginx限制ip并发数
    nginx 403错误
    ubuntu 支持中文
    CentOS 5 上使用yum同时安装32位和64位包的解决方法
    rhel yum报错
    因为swap分区无法启动
  • 原文地址:https://www.cnblogs.com/codingHeart/p/6529556.html
Copyright © 2011-2022 走看看