codingHeart

返回顶部

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

 

posted on 2017-03-10 11:01  codingHeart  阅读(243)  评论(0)    收藏  举报

导航