1. Two Sum [Array] [Easy]

 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: input: nums = [2, 7, 11, 15] , target=9.

output:  [0, 1]

给定一个整型数组与一个目标数,输出两个数相加为此目标数的下标。(只有一个结果,且每个数只能使用一次)

 

1. 最简单的方法就是双重循环,取到之后return. 不过太耗时了,肯定不符合要求。

所以我在每次循环里面,查找数组有没有另一个值。(做算法题的话应该不能使用.ToList()这样的方法吧?)

public int[] TwoSum(int[] nums, int target) {        
        for(int index = 0; index < nums.Length; index++){
            int element = nums[index];
            int otherElement = target - element;//查找是否存在
            int otherIndex = nums.ToList().IndexOf(otherElement);//主要是这一步
            if(otherIndex != -1 && otherIndex != index){
                return new int[2]{index,otherIndex};   
            }
        }
        return null;
}

耗时:652ms.  内存:48.7MB

 

2. 在上面的基础上从把数组转换成字典,从其中查找,查找速度应该比数组快。

 1 public int[] TwoSum(int[] nums, int target) {      
 2         Dictionary<int, int> dic = new Dictionary<int, int>();
 3         for(int index = 0; index < nums.Length; index++){
 4             dic[index] = nums[index];
 5         }
 6         for(int index = 0; index < nums.Length; index++){
 7             int element = nums[index];
 8             int otherElement = target - element;//查找是否存在
 9             bool containsValue = dic.ContainsValue(otherElement);//主要是这一步
10             if(containsValue){
11                 int foundKey = -1;
12                 foreach (int key in dic.Keys){
13                     if (dic[key] == otherElement && key != index){ 
14                         foundKey = key;
15                         return new int[2]{index, foundKey};
16                     }
17                 }
18             }
19         }
20         return null;
21     }

耗时:788 ms.  内存:29.6 MB  不过找到元素后还得取出下标,又是一个循环。不过内存占用变小了。

 

3. 只需要一个循环。 每次查找当前元素的匹配项前,把前一个数放入字典中,从字典查找匹配项。如果匹配到了,则当前index为后一个数的下标。

1 public int[] TwoSum(int[] nums, int target) {      
2         Dictionary<int, int> dic = new Dictionary<int, int>();
3         for(int index = 0; index < nums.Length; index++){
4             if(dic.ContainsKey(target - nums[index]))
5                 return new int[]{dic[target - nums[index]],index};
6             dic[nums[index]] = index;
7         }
8       return null;
9 }

252 ms. 29.4 MB。题目中说结果只有一个,所以就算是数组元素作为key也没事。而且通过key容易找出value下标值。

 

但是如果会有多个重复值,上述就不适用了,给同一个key赋值,value会被覆盖掉。

例如 input:[5,5,8,3]  target=13。 本应该输入[0, 2], 可是上述结果却输出了[1, 2].

因此需要使用下标作为key才行. 不过此时通过value快捷查找key又成了问题。看看以后会不会有这类题目。

 

posted @ 2019-03-10 20:45  汪小饭  阅读(164)  评论(0编辑  收藏  举报