【LeetCode系列】 Day1 两数之和 Two Sum

题目:

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。


我的解答:两个循环嵌套,暴力解答,时间复杂度为O(n²)。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        for(int i = 0; i < nums.length; i++){
            for(int j = i + 1; j < nums.length; j++){
                if(nums[i] + nums[j] == target){
                    result[0] = i;
                    result[1] = j;
                }
            }
        }
        return result;
    }
}

优化解答:

    为了减少时间复杂度可以这样考虑,先选定一个数假设是nums[i],因为target已经确定,则只需要在数组中找是否存在数字target - nums[i]即可。

    问题则转化为:如何在数组中快速找到某一个元素——哈希查找哈希查找是通过“哈希值”进行复杂度为O(1)的查找的一种方法。更详细的java中的HashMap的介绍可以看:http://www.cnblogs.com/skywang12345/p/3310835.html

    需要说明的是,虽然哈希查找速度很快,但是在初始化时时间复杂度和空间复杂度都为O(n)。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> numsHash = new HashMap<Integer, Integer>();
        int[] results = new int[2];
        for(int i = 0; i < nums.length; i++){
            numsHash.put(nums[i], i);                  //注意初始化时key是nums[i]的值,value是数组下标
        }
        for(int i = 0; i < nums.length; i++){
            int num = target - nums[i];
            if(numsHash.containsKey(num) && (numsHash.get(num) != i)){
                results[0] = i;
                results[1] = numsHash.get(num);
                break;
            }
        }
        return results;
    }
}

    更简洁的函数:在初始化HashMap的同时,往回检查在已有哈希表中寻找是否有需要找的那个数。此时i是数组中靠后的下标。

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

    还有一种在数组中找到某一个元素的方法:二分查找。但二分查找对有序数组使用较方便,时间复杂度为O(logn)。对该提而言若要使用二分查找则需要先对数组进行排序,考虑到排序的时间消耗且排序后的数组下标将有所变化,建议该题使用HashMap效果最好。

附上运行时间对比截图:


猜你喜欢

转载自blog.csdn.net/u014586129/article/details/80168521
今日推荐