给定一个整数数组和一个目标值,找出数组中和为目标值的两个数(同样的元素只能用一次)

解决方案

笔者最近会一直持续更新数据结构跟算法的题目(秋招要来了) – 是我根据左神上课整理的一些代码
数据结构跟算法 – 点击跳转
还是挺有价值的 – 这段时间基础班的会一直更新
为了正义,所有资源免费送,你想要的都给你,做人就是这么讲究.唯一要求,别去告我.

*方法一:暴力法:

public static int[] twoSum01(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};
            }
        }
    }
    // return null;
    throw new IllegalAccessError("No two solution");
}

复杂度分析:

由于有两次for循环,遍历一次时间复杂度就是O(n),那么两次时间复杂度就是O(n2)[n的平方]
空间复杂度是O(1)

*方法二:两遍Hash表

public static int[] twoSum02(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    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");
}

分析:

为了对运行时间复杂度进行优化,我们需要一种更有效的方法来检查数组中是否存在目标元素,如果存在,我们需要
找出它的索引.保持数组中的每个元素与其索引相互对应的最好办法就是hHsh表
时间复杂度:O(n), 我们把包含有 nn 个元素的列表遍历两次。由于哈希表将查找时间缩短到 O(1)O(1) 
,所以时间复杂度为 O(n)O(n)。
空间复杂度:O(n)O(n), 所需的额外空间取决于哈希表中存储的元素数量,该表中存储了 nn 个元素。

*方法三:一遍Hash表:

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

LeetCode网站

需要算法学习资源,java学习资源,框架深入资源,大数据学习资源,网络学习资源,计算机考研学习资源的同学请加qq:2297581773或者微信:18838927694

笔者是从乐扣网站上学习而来

猜你喜欢

转载自blog.csdn.net/qq_38200548/article/details/80643394