• 两数之和(Java版)


    题目描述:
    给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

    你可以按任意顺序返回答案。

    方法一:
    使用两个for循环进行遍历,第一个循环确定第一个数num[i],第二个循环进行判断数组中i后的其他数字num[j]num[i]相加是否等于target,如果能则返回。
    时间复杂度为O(n²)

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] res = 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){
                        res[0] = i;
                        res[1] = j;
                        return res;
                    }
                }
            }
            return res;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    方法二:
    由于哈希查找的时间复杂度为 O(1),所以可以利用哈希容器 map 降低时间复杂度。
    时间复杂度为O(n)

    1.先定义一个哈希表,此时哈希表为空
    2.循环遍历,如果哈希表中存在key跟当前遍历时的值相加后等于target即满足条件可返回,如果不是则将其添加到哈希表中,遍历num[0]时,哈希表中为空,所以一定不满足条件,会将其添加到哈希表中,在遍历数组中其他值的过程中,这个num[0]会跟其他值相加匹配是否等于target,也就是通过for循环确定第一个值,哈希表查询确定第二个值,总的时间复杂度就是O(n).

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            Map<Integer, Integer> map = new HashMap<>();  //空的哈希表
            for(int i = 0; i< nums.length; i++) {
                if(map.containsKey(target - nums[i])) {
                    return new int[] {map.get(target-nums[i]),i};
                }
                map.put(nums[i], i);
            }
            throw new IllegalArgumentException("No two sum solution");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  • 相关阅读:
    docker进入容器报:Error response from daemon Container is not running
    YUM源的几种常见方式
    【三维重建】3D Gaussian Splatting:实时的神经场渲染
    java-net-php-python-45ssm校园小商品二手交易系统计算机毕业设计程序
    Ps:画布大小
    JS返回NodeList和HTMLCollection详解
    Java进阶篇--AQS(AbstractQueuedSynchronizer)
    数据库开发-MySQL基础DQL和多表设计
    goweb入门
    排序 (爱思创算法四)(期中测试)(答案记录)
  • 原文地址:https://blog.csdn.net/m0_53951384/article/details/133763186