您的位置:首页 > 编程语言 > Java开发

Leetcode旅途一

2016-02-22 23:00 483 查看
No.1:Two Sum

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


初见思想方法:

在一个给定的整数数组中,找出两个不同元素的和为给定目标整数,返回一个数组,数组内存有这两个不同元素的下标位置。

容易想到的方法是两层for循环,遍历查询数组,通过加运算是否符合条件。易得,该算法时间复杂度为O(n^2)。

实现代码如下:

    public int[] twoSum(int[] nums, int target) {

        int[] a = new int [2];

        boolean flag = false;

        for(int i = 0; i < nums.length; i++){

        if(flag) break;

            for(int j = 0; j < nums.length; j++){

            if(flag) break;

                if(nums[i] + nums[j] == target){

                    a[0] = i;

                    a[1] = j;

                    flag = true;

                }

            }

        }

        return a;

    }

但时间代价较大,对于nums数组规模较大的时候,效率显得较慢。

改进方法:

为什么上述方法效率较低,主要是做了两层嵌套遍历,因此效率较低。因此可以通过减少遍历的次数,来提供算法的效率。

在数组中查找相应元素,需要对数组进行遍历来查询,遍历一个n个元素的数组,需要时间复杂度为O(n),而对于哈希表中查询一个元素的时间复杂度则只需O(1)。

因此我们可以考虑使用哈希表能替代数组。

再者,寻找符合要求的这两个数,可以转化为对于已知的一个数,目标数和它的差(即为第二个数)是否存在于哈希表中,利用了哈希表键值对的优点,进而优化效率。

具体实现代码如下:

    public int[] twoSum(int[] nums, int target) {

        int[] a = new int [2];

        HashMap<Integer, Integer> map = new HashMap<>();

        for(int i = 0; i < nums.length; i++){

        Integer n = map.get(nums[i]);

        if(n == null) 

        map.put(nums[i], i);

        n = map.get(target - nums[i]);

        if( n != null && n < i){

        a[0] = n;

        a[1] = i;

        return a;

        }

       

        }

        return a;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Java