LeetCode第1题

LeetCode第一题:两数之和

题目描述

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

解法一

两层for循环时间复杂度:O(n²)

public int[] twoSum(int[] nums, int target) {
            int[] aa = new int[2];
            for(int i = 0;i < nums.length - 1; i++) {
                for(int j = i+1;j < nums.length; j++) {
                    if(nums[i] + nums[j] == target) {
                       return new int[]{i,j};
                    }
                }
            }
            throw new IllegalArgumentException("No Answer");
        }

解法二

使用hashmap存储数组中的值(hashmap查找时间复杂度O(1))
==注意:==存入map的key为数组中的值,value是数组值对应的下标,方便使用containsKey()方法判断数组中是否存在complement值,

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];
            //存在,返回complement的value值(即complement的下标)和当前for循环到的下标值;不存在,添加进map中
            if(map.containsKey(complement)) {
                return new int[] {map.get(complement),i};
            }
            map.put(nums[i],i);
        }
        throw new IllegalArgumentException("No Answer!");
    }
发布了5 篇原创文章 · 获赞 0 · 访问量 44

猜你喜欢

转载自blog.csdn.net/weixin_42610002/article/details/104050524