LeetCode one Two Sum

LeetCode one Two Sum (JAVA)

 

简介:给定一个数组和目标值,寻找数组中符合求和条件的两个数.

问题详解:

给定一个数据类型为int的数组,一个数据类型为int的目标值target,要求是在数组中寻求两个数字,使得两个数求和的值等于给定的target,要求以数组返回符合条件的索引.

技巧:可以假设数组中没有重复元素,因为我们只返回一个符合条件的数组,所以数组中只需要一个符合要求的数字就可以了.

 

举例:

给定数组 nums={5,8,7,2,11},target= 10,

因为nums[1]+nums[3]=8+2=10,

所以返回[1,3].

 

注意:

1.数组下标不能重复

错解:nums[0]+nums[0]=5+5=10,

返回[0,0].

2.要考虑到没有符合的结果时的处理.

 

JAVA实现方法一:暴力遍历,两层循环,不推荐(第一次愚蠢实现)

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

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

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

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

                return new int[] { i, j };

            }

        }

    }

    throw new IllegalArgumentException("No two sum solution");

}

 

学习之路:

官方实现一 : 双层遍历.

优点:

1.代码的简洁性.

2.用throw方法处理无结果.

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

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

    for (int i = 0; i < nums.length; i++) {//存放数组数据

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

    }

    for (int i = 0; i < nums.length; i++) {//判断结果

        int complement = target - nums[i];

        if (map.containsKey(complement) && map.get(complement) != i) {

            return new int[] { i, map.get(complement) };

        }

    }

    throw new IllegalArgumentException("No two sum solution");

}

复杂度分析:

时间复杂度 :近似于O(n^2):双层遍历,方法执行了n*n次.

空间复杂度 :近似于 O(1):变量的定义为常数.

 

官方实现二 : 利用HashMap两次遍历

先存放数组数据,再判断Map数据.

优点:

1.利用Hash表通过空间交换时间的方法提高查找时间.

2.因为不需要两个重复的数字,所以不会与Map中键的特性冲突.

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

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

    for (int i = 0; i < nums.length; i++) {//存放数组数据

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

    }

    for (int i = 0; i < nums.length; i++) {//判断结果

        int complement = target - nums[i];

        if (map.containsKey(complement) && map.get(complement) != i) {

            return new int[] { i, map.get(complement) };

        }

    }

    throw new IllegalArgumentException("No two sum solution");

}

复杂度分析:

时间复杂度 :近似于O(n):都是单层遍历,方法执行了n次.

空间复杂度 :近似于 O(n):一次遍历,变量定义了n次.

 

LeetCode官方实现三 : 利用HashMap两次遍历

在存放数据的过程中判断结果.

优点:

1.提高了代码的简洁性

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

}

复杂度分析:

时间复杂度 :近似于O(n):一次遍历,方法执行了n次.

空间复杂度 :近似于 O(n):一次遍历,变量定义了n次.

 

随记:

length——数组的属性;

length()——String的方法;

size()——集合的方法;

put()——Map的添加方法 ;

add()——Collection的添加方法;

 

小白刷题之路,请多指教— — 要么大器晚成,要么石沉大海

 

猜你喜欢

转载自www.cnblogs.com/lalalaczq/p/10659307.html
今日推荐