<Leetcode> Two Sum

1. 题目

这里写图片描述

2. 自己的解法

  就是纯暴力,比较好想,一般大部分没有系统学习算法的都会有这样的思路。时间复杂度为 O ( n 2 )

int* twoSum(int* nums, int numsSize, int target){
    int i,j;
    int * result;
    result=malloc(sizeof(int)*2);
    for(i=0;i<numsSize;i++){
        for(j=i+1;j<numsSize;j++)
            if(nums[i]+nums[j] == target){
                result[0]=i;
                result[1]=j;
            }                          
    }
    return result;
}

3. 优质解法

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}

It turns out we can do it in one-pass. While we iterate and inserting elements into the table, we also look back to check if current element’s complement already exists in the table. If it exists, we have found a solution and return immediately.

4. 总结

  将陌生问题转化为熟悉的问题,原题目可以转化为在一定范围内查找某数。从数据结构的角度出发,散列的查找时间复杂度为 O ( 1 ) ,插入时间为 O ( 1 ) ,所以使用散列可以将暴力解法的 O ( n 2 ) 降低到线性的 O ( n )
  另外C语言没有现成的hash库接口,如果主打语言是C语言,这个题自己还需要实现一个散列,根据笔者在DSAA的记录,自己实现的散列时间复杂度是否可以保持 O ( 1 ) 都是不好说的。所以从这里笔者也第一次感觉到C++ STL的方便性。

猜你喜欢

转载自blog.csdn.net/lovestackover/article/details/80277981